How to shuffle an array - JavaScript

Mo Ibra

Mo Ibra

Jan 2, 2023

In this article we will learn how to shuffle an array in JavaScript.

It is very common to shuffle an array in JavaScript in JavaScript.


Problem

Now we have a problem, which is that we want to shuffle an array.

Imagine you have a array like this:

[1, 2, 3, 4, 5];

And we want to shuffle an array to became output like this:

// Shuffle more than once
[2, 1, 5, 4, 3];
[1, 1, 4, 3, 5];
[4, 5, 3, 1, 2];

How to solve this problem

To solve this problem we will use Fisher-Yates shuffle algorithm.


Solution:

As we said before, we can solve this problem using Fisher-Yates shuffle algorithm.

Let's see an example

let array = [1, 2, 3, 4, 5];

for (let i = array.length - 1; i >= 1; i--) {

    let j = Math.floor(Math.random() * (i + 1));

    let temp = array[j];
    array[j] = array[i];
    array[i] = temp;
}

console.log(array);

Output

[ 3, 5, 2, 4, 1 ]

Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: