0
0
JavascriptProgramBeginner · 2 min read

JavaScript Program to Shuffle Array Elements Randomly

Use the Fisher-Yates shuffle algorithm in JavaScript like this: 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

Input[1]
Output[1]
Input[1, 2, 3, 4, 5]
Output[3, 1, 5, 2, 4]
Input[]
Output[]
🧠

How to Think About It

To shuffle an array, think of picking each element and swapping it with another element at a random position. This way, every element has an equal chance to end up anywhere. We do this from the end of the array to the start, swapping each element with a random earlier element or itself.
📐

Algorithm

1
Start from the last element of the array.
2
Pick a random index from 0 to the current element's index.
3
Swap the current element with the element at the random index.
4
Move one element backward and repeat until the first element.
💻

Code

javascript
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));
Output
Shuffled array: [3, 1, 5, 2, 4]
🔍

Dry Run

Let's trace shuffling [1, 2, 3, 4, 5] through the code

1

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]

2

i = 3

Random j between 0 and 3, say j = 0; swap elements at 3 and 0: [4, 2, 5, 1, 3]

3

i = 2

Random j between 0 and 2, say j = 1; swap elements at 2 and 1: [4, 5, 2, 1, 3]

4

i = 1

Random j between 0 and 1, say j = 1; swap elements at 1 and 1 (no change): [4, 5, 2, 1, 3]

ijArray state after swap
42[1, 2, 5, 4, 3]
30[4, 2, 5, 1, 3]
21[4, 5, 2, 1, 3]
11[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

Using sort with random comparator
javascript
const shuffle = array => array.sort(() => Math.random() - 0.5);

const arr = [1, 2, 3, 4, 5];
console.log('Shuffled array:', shuffle(arr));
This is simpler but less reliable and can produce biased results.
Creating a new shuffled array
javascript
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));
This does not modify the original array but uses extra space.

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.

ApproachTimeSpaceBest For
Fisher-Yates shuffleO(n)O(1)Efficient, unbiased shuffling in place
Sort with random comparatorO(n log n)O(1)Simple but biased and slower
New shuffled arrayO(n^2)O(n)Preserving original array but slower and uses extra space
💡
Use the Fisher-Yates algorithm for unbiased and efficient shuffling.
⚠️
Using sort(() => Math.random() - 0.5) can cause uneven shuffling and should be avoided for serious use.