Last active
December 15, 2020 13:02
-
-
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/
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
/** | |
* 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