How to Shuffle an Array using JavaScript?

Shuffling is a process of rearranging items in random order. So, when we say that shuffle an array, it means we are rearranging the array items in random order.

For instance, if we have an array [1, 2, 3] then after shuffling it can result in [2, 1, 3] or [1, 3, 2] or [3, 1, 2], etc.

The quickest way to shuffle an array is to call the sort() method on it and use the Math.random() method to randomize the array elements.

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Shuffle the array
arr.sort(()=>Math.random() - 0.5);

console.log(arr);
// Output: [6, 7, 10, 2, 4, 8, 9, 3, 1, 5]

How does it work?

The sort() method by default sorts the array into ascending order.

But the beauty of the sort() method is that it can take a compare function as a callback where we can build our own logic to sort or rearrange the array items. That’s exactly what we did in the above example.

Array.sort(compareFun);

The sort() method one by one passes a pair of two consecutive array elements to the compare function in order to sort the array.

The compare function as a result returns either a positive, negative or zero value to the sort() method and the sort() method rearranges the array elements according to this result.

function compareFun(a, b){
    if(a<b){
        return -1;
        // Places a before b in the array
    }
    else if(a>b){
        return 1;
        // places a after b in the array
    }
    else{
        return 0;
        // Keep a and b in original order
    }
}

There are three possible values that the compareFun could return:

  1. Negative – Places a before b
  2. Positive – Places a after b
  3. Zero – Keep original order of a and b

As we want to shuffle the array items, therefore, we have to randomly return a positive, negative or zero value from the compare function.

To achieve that we used the Math.random() function.

The Math.random() function returns a random floating-point value between 0 and 1:

console.log(Math.random());  // 0.38
console.log(Math.random());  // 0.75
console.log(Math.random());  // 0.25

But, in our case, we want to return a positive, negative or zero value. Therefore, we subtracted 0.5 from this random value.

It means if random number is greater than 0.5, the compare function returns a positive value, if it is less than 0.5, the compare function returns a negative value and if it is 0, the compare function returns 0.

console.log(Math.random() - 0.5);  // -0.45
console.log(Math.random() - 0.5);  // 0.00
console.log(Math.random() - 0.5);  // 0.22

As the result of Math.random() - 0.5 is totally random, therefore, the sort method rearranges the array items in a random order.


Method 2: By Manually Swapping the Array Items

We can also shuffle the array without using the sort() method.

In this method, we generate a random array index and swap item at this index with the current array item.

See the following program:

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

for(let i=arr.length-1;i>0;i--){
    
    // Generate a random index
    let j = Math.floor(Math.random()*(i+1));
    
    // Swap element at index i with element at index j
    let temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}

console.log(arr);
// Output: [6, 2, 3, 5, 9, 8, 7, 4, 10, 1]

As you can see, we are generating a random number between 0 and arr.length-1 and storing it in a variable j. After that we are swapping the item at index j with the array item at index i.

Thanks for reading.


Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.