How to make sure the randomness is really random.
It might be tempting to use just Math.random()
but it will not produce fair results.
const notRandomEnough = (array) => array.sort(() => Math.random() - 0.5);
The Fisher–Yates shuffle algorithm example in JavaScript
The Fisher–Yates shuffle is an algorithm for generating a random permutation of a finite sequence—in plain terms, the algorithm shuffles the sequence.
Fisher–Yates shuffle on Wikipedia.
See the example below for JavaScript implementation of the modern Fisher–Yates shuffle algorithm.
/**
* Shuffle an array using the modern Fisher–Yates shuffle algorithm.
*
* https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm
*
* @param {array} array
* @returns {array}
*/
function shuffleArray(array) {
let currentIndex = array.length;
while (--currentIndex > 0) {
const randomIndex = Math.floor(Math.random() * (currentIndex + 1));
[array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]];
}
return array;
}
Share
Thanks for reading. If you liked it, consider sharing it with friends via:
Let's be in touch!
Don't miss other useful posts. Level up your skills with UX, web development, and productivity tips via e-mail.
Comments
If you want to comment, write a post on social media and @mention me or write to me directly on the contact page.