Skip to content

Instantly share code, notes, and snippets.

@damianwajer
Last active December 15, 2020 13:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save damianwajer/13b8e22a5206ff7f655fbc1e38c2dd55 to your computer and use it in GitHub Desktop.
Save damianwajer/13b8e22a5206ff7f655fbc1e38c2dd55 to your computer and use it in GitHub Desktop.
[JavaScript] Shuffle an array using the modern Fisher–Yates shuffle algorithm | https://www.damianwajer.com/blog/random-array-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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment