Code Snippets
/

Shuffle an Array (Fisher-Yates)

Shuffle an Array (Fisher-Yates)

The naive `array.sort(() => Math.random() - 0.5)` looks fine until you measure it: the distribution is heavily biased and some pairs swap with much higher probability than others. The Fisher-Yates shuffle is the standard correct answer in O(n) time with uniform output. This snippet shows the in-place version, a non-mutating wrapper, and an empirical demo of why the popular `sort`-based trick is biased.

JavaScript
Easy
3 snippets
arrays
code-template
array-manipulation-patterns

1,068 views

7

function shuffle(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 deck = [1, 2, 3, 4, 5];
shuffle(deck);
console.log(deck.length === 5);
console.log([...deck].sort((a, b) => a - b));
// [1, 2, 3, 4, 5] (same elements, scrambled order)

The Fisher-Yates shuffle walks the array from the end and at each position picks a random index in [0, i], then swaps. The crucial detail is that the random range shrinks each step (i + 1), which is what gives every permutation an equal probability. Anything that picks from [0, length) for every iteration produces a biased distribution. The algorithm is O(n) time, O(1) extra space, and is the textbook correct shuffle. We verify by sorting a copy and confirming the original elements are preserved.