Categories
JavaScript Answers

How to Shuffle a JavaScript Array?

Spread the love

Shuffling a JavaScript array is something that we’ve to do sometimes.

In this article, we’ll look at how to shuffle a JavaScript array.

Swapping Array Entries Randomly

One way to shuffle a JavaScript array is to swap different array entries’ positions randomly.

For instance, we can write:

const shuffleArray = (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]];
  }
}

const arr = [1, 2, 3]
shuffleArray(arr)
console.log(arr)

In the shuffleArray function, we loop through the array with the for a loop.

Then we pick a random index from the array with the Math.random method.

And then we do the swap after that by getting the entries and assigning them to the other item’s position.

array is changed in place.

So after calling shuffleArray on arr , we get an array with the items swapped in position.

This is called the Durstenfeld shuffle, which is an optimized version of the Fisher-Yates shuffle algorithm.

The sort Method and Math.random

We can use the sort method and Math.random together to shuffle an array.

For instance, we can write:

const arr = [1, 2, 3].sort(() => .5 - Math.random());
console.log(arr)

We return a random number between -0.5 and 0.5 in the callback to lets us shuffle the array.

This is because if the returned number is negative, then the position of 2 elements it’s iterating through stays the same.

Otherwise, they’re swapped.

However, this is biased and it’s also slow.

But this is the easiest way to shuffle an array with JavaScript.

Conclusion

There’re a few ways to shuffle an array with JavaScript.

They all needs the Math.random method to pick a random number.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *