For more tips like this, sign up to the weekly newsletter!

Shuffle an array the right way

When you want an array with its elements in a random order, you shuffle it. There are a few algorithms to properly do it, the most widely used being the Fisher-Yates Shuffle.

It's rather simple, only three lines of pseudocode. Most libraries that provide a shuffle function (for ex. Lodash) use it.

Its usage is simple: _.shuffle(array)

In the case of Lodash, it creates a new array and does not modify the parameter. But if you use a different library, it might shuffle in-place. In that case, copy the array before passing in: otherlib.shuffle([...arr]).

The algorithm is correct so that every value has an equal chance of ending up in each position. This is the type of correctness you expect from a shuffle algorithm.

A naive but wrong solution

If you google how to shuffle an array, you may stumble on a short, library-less version:

array.sort(() => .5 - Math.random());

At first glance, it indeed moves the elements in a seemingly random way, but unfortunately, this algorithm is not correct. The distribution is heavily skewed.

For example, if you shuffle arrays having a length of 5 for 100.000 times, you can see a distribution of elements for the first index similar to:

    "1": 30642,
    "2": 30803,
    "3": 20596,
    "4": 11757,
    "5": 6202

The key takeaway is to use proven algorithms when you work with randomness, as it is not trivial to distinguish the "it is random" from the "it seems random".

Try it
References
Learn more: