How To Shuffle An Array In JavaScript

In this article we’ll take a look at a couple of ways to shuffle an array in JavaScript.

The first and simplest way to shuffle an array in JavaScript is to provide a custom function to a .sort().

    const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    array.sort((a, b) => 0.5 - Math.random());

As the function we pass to .sort() is looking for either a positive or negative number to either move the item ‘up’ or ‘down’ in the array we get a random distribution of items.

This works for a rough-and-ready approach but might not give you a truly random shuffle.

If you read some articles like you’ll see that the custom sort function is flawed (although I can’t give you a definitve answer as to why that is!).

If you need to shuffle an array and have a truly random distribution of items, you need to implement the Fisher-Yates algorithm.

Fisher-Yates algorith

Luckily for us, it's not too complicated:

    const shuffleArray = array => {
        for (let i = array.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            const temp = array[i];
            array[i] = array[j];
            array[j] = temp;

As you can see it’s just a case of looping through the array (from the end to the start) and picking a random item from the array and swapping it with the item in the current iteration.

You can use the above function to shuffle an array in JavaScript and get a random result each time.