Ways to Shuffle an Array in JavaScript

Photo by Joseph Two on Unsplash

Ways to Shuffle an Array in JavaScript

Shuffling an array is a common task in programming, often used in games, simulations, or any application that requires randomization. Here are a few alternative ways to shuffle an array in JavaScript:

1. Fisher-Yates (Knuth) Shuffle

The Fisher-Yates algorithm is a classic and efficient way to shuffle an array. It ensures that each permutation of the array is equally likely.

function fisherYatesShuffle(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]];
    }
    return array;
}

const arr1 = [1, 2, 3, 4, 5];
console.log(fisherYatesShuffle(arr1));

2. Sort with Random Comparator

This method uses the sort function with a random comparator. It is shorter but not as efficient or reliable as the Fisher-Yates shuffle.

function randomSortShuffle(array) {
    return array.sort(() => Math.random() - 0.5);
}

const arr1 = [1, 2, 3, 4, 5];
console.log(randomSortShuffle(arr1));

3. Random Index Swap

This method iterates through the array and swaps each element with a randomly selected element.

function randomIndexSwapShuffle(array) {
    for (let i = 0; i < array.length; i++) {
        const j = Math.floor(Math.random() * array.length);
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
}

const arr1 = [1, 2, 3, 4, 5];
console.log(randomIndexSwapShuffle(arr1));

Conclusion

While there are various ways to shuffle an array in JavaScript, the Fisher-Yates shuffle is generally the most reliable and efficient. The random sort and random index swap methods can work in certain scenarios but may not provide a perfectly uniform shuffle.