Shuffling an Array in Javascript

January 14, 2019

There are many ways to shuffle an arrays. Various algorithms offer different levels of performance, and specially bias!

Here's a quick method:

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

    return array
}

Now among shuffling algorithms, the Fisher-Yates algorithm is known to be the most unbiased algorithm.

Here's how to implement Fisher-Yates (AKA Knuth Shuffle):

// http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
const shuffleArray = array => {
    let currentIndex = array.length
    let temporaryValue;
    let randomIndex;

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {
        // Pick a remaining element...
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;

        // And swap it with the current element.
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }

    return array;
}

More on the Fisher-Yates algorithm