Durstenfeld shuffle
// http://en.wikipedia.org/wiki/Fisher-Yates_shuffle#The_modern_algorithm | |
// https://stackoverflow.com/a/12646864/2684520 | |
// Pre-ES6 | |
/** | |
* Randomize array element order in-place. | |
* Using Durstenfeld shuffle algorithm. | |
*/ | |
function shuffleArray(array) { | |
for (var i = array.length - 1; i > 0; i--) { | |
var j = Math.floor(Math.random() * (i + 1)); | |
var temp = array[i]; | |
array[i] = array[j]; | |
array[j] = temp; | |
} | |
} | |
// ES6+ | |
function shuffleArray(array) { | |
for (let i = array.length - 1; i > 0; i--) { | |
let j = Math.floor(Math.random() * (i + 1)); | |
[array[i], array[j]] = [array[j], array[i]]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment