Skip to content

Instantly share code, notes, and snippets.

@duplaja
Created September 12, 2021 22:09
Show Gist options
  • Save duplaja/6010923fce070c57c5a7d583e0a2e98f to your computer and use it in GitHub Desktop.
Save duplaja/6010923fce070c57c5a7d583e0a2e98f to your computer and use it in GitHub Desktop.
Custom JS Shuffle - Keep First
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);
}
@duplaja
Copy link
Author

duplaja commented Sep 12, 2021

Shuffles a JS array, leaving the first element in place.

@KevinBatdorf
Copy link

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