Created
September 12, 2021 22:09
-
-
Save duplaja/6010923fce070c57c5a7d583e0a2e98f to your computer and use it in GitHub Desktop.
Custom JS Shuffle - Keep First
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function customShuffle(x) { | |
var y = x.slice(1, x.length); | |
var j, t, i; | |
for (i = y.length - 1; i > 0; i--) { | |
j = Math.floor(Math.random() * (i + 1)); | |
t = y[i]; | |
y[i] = y[j]; | |
y[j] = t; | |
} | |
return [x[0]].concat(y); | |
} |
Here's another way to do it
const customShuffle = (theArray) => [
theArray[0],
...theArray.slice(1, -1)
.map(n =>[Math.random(), n])
.sort((a, b) => a[0] - b[0])
.map(n => n[1])
]
customShuffle([1,2,3,4,5,6,7,8,9])
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Shuffles a JS array, leaving the first element in place.