Shuffle an Array in JavaScript
The most common way to shuffle an array in JavaScript is by using the Fisher-Yates shuffle algorithm.
This algorithm efficiently shuffles an array in place. Here’s a straightforward way to implement this algorithm in JavaScript (I'll share an explanation after the code).
Also, while looking for the algorithm, I found this. It's a great visualization/explanation of the algorithm in action.
function shuffleArray(array) { for (let i = array.length - 1; i > 0; i--) { // Generate a random index lower than the current element index const j = Math.floor(Math.random() * (i + 1)); // Swap elements i and j [array[i], array[j]] = [array[j], array[i]]; } return array; } // Usage const myArray = [1, 2, 3, 4, 5]; shuffleArray(myArray); console.log(myArray); // Outputs random order like: [3, 5, 4, 1, 2]
How It Works
- We loop over the array from the end of the array and decrement down to the second element.
- Randomly select an index from
0
to the current indexi
. - Swap the element at the current index
i
with the element at the randomly selected indexj
.
When you run the function with an example array, it randomly shuffles the elements each time you execute it.