Skip to content

Instantly share code, notes, and snippets.

@masautt
Created September 6, 2019 19:25
Show Gist options
  • Save masautt/5e4b063c06153d6c82a02543aa89f541 to your computer and use it in GitHub Desktop.
Save masautt/5e4b063c06153d6c82a02543aa89f541 to your computer and use it in GitHub Desktop.
How to shuffle an array in JavaScript?
function shuffleArray(arr) {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
let arr = [8,6,7,5,3,0,9];
console.log(shuffleArray(arr)); // --> [ 6, 0, 8, 7, 3, 5, 9 ]
// Replaces existing array
console.log(arr); // --> [ 6, 0, 8, 7, 3, 5, 9 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment