Created
September 6, 2019 19:25
-
-
Save masautt/5e4b063c06153d6c82a02543aa89f541 to your computer and use it in GitHub Desktop.
How to shuffle an array in JavaScript?
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 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