JavaScript Program to Shuffle Array Elements Randomly
function shuffle(array) { for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [array[i], array[j]] = [array[j], array[i]]; } return array; } to shuffle an array in place.Examples
How to Think About It
Algorithm
Code
function shuffle(array) { for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [array[i], array[j]] = [array[j], array[i]]; } return array; } const arr = [1, 2, 3, 4, 5]; console.log('Shuffled array:', shuffle(arr));
Dry Run
Let's trace shuffling [1, 2, 3, 4, 5] through the code
Start with i = 4 (last index)
Random j chosen between 0 and 4, say j = 2; swap elements at 4 and 2: [1, 2, 5, 4, 3]
i = 3
Random j between 0 and 3, say j = 0; swap elements at 3 and 0: [4, 2, 5, 1, 3]
i = 2
Random j between 0 and 2, say j = 1; swap elements at 2 and 1: [4, 5, 2, 1, 3]
i = 1
Random j between 0 and 1, say j = 1; swap elements at 1 and 1 (no change): [4, 5, 2, 1, 3]
| i | j | Array state after swap |
|---|---|---|
| 4 | 2 | [1, 2, 5, 4, 3] |
| 3 | 0 | [4, 2, 5, 1, 3] |
| 2 | 1 | [4, 5, 2, 1, 3] |
| 1 | 1 | [4, 5, 2, 1, 3] |
Why This Works
Step 1: Loop from the end
We start from the last element and move backward to ensure each element gets swapped exactly once.
Step 2: Pick a random index
For each element, we pick a random index from the start up to the current position to swap with.
Step 3: Swap elements
Swapping the current element with the randomly chosen one mixes the array without bias.
Alternative Approaches
const shuffle = array => array.sort(() => Math.random() - 0.5); const arr = [1, 2, 3, 4, 5]; console.log('Shuffled array:', shuffle(arr));
function shuffleNew(array) { const copy = array.slice(); const result = []; while (copy.length) { const index = Math.floor(Math.random() * copy.length); result.push(copy.splice(index, 1)[0]); } return result; } const arr = [1, 2, 3, 4, 5]; console.log('Shuffled new array:', shuffleNew(arr));
Complexity: O(n) time, O(1) space
Time Complexity
The algorithm loops through the array once, swapping elements, so it runs in linear time O(n).
Space Complexity
It shuffles the array in place without extra arrays, so space complexity is O(1).
Which Approach is Fastest?
The Fisher-Yates shuffle is the fastest and most reliable compared to sorting with random or creating new arrays.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Fisher-Yates shuffle | O(n) | O(1) | Efficient, unbiased shuffling in place |
| Sort with random comparator | O(n log n) | O(1) | Simple but biased and slower |
| New shuffled array | O(n^2) | O(n) | Preserving original array but slower and uses extra space |
sort(() => Math.random() - 0.5) can cause uneven shuffling and should be avoided for serious use.