Skip to content
jshacks.dev
Fundamentals

How to Shuffle an Array Correctly With Fisher Yates

Shuffle an array fairly with Fisher-Yates, not sort with Math.random. See a seeded test that proves the bias, sampling, crypto randomness and off-by-one bugs.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, TypeScript and npm logos.

The most popular one-liner for shuffling an array in JavaScript is array.sort(() => Math.random() - 0.5), and it is wrong. It looks right, it produces a different order each time, and a quick look at the output finds nothing odd, but the result is not a fair shuffle: some orders come up more often than others, and how much depends on the engine, since the comparator breaks the rules that sort relies on. The correct algorithm is older than JavaScript, Fisher-Yates, and is five lines: walk the array from the end, swap each position with a randomly chosen position at or before it. This post shows the algorithm with a seeded random generator so the output is exact, proves with a count of outcomes that the correct version is uniform and a plausible-looking variant is not, explains why the sort trick fails, and covers copying, sampling a few items, secure randomness and the mistakes that produce a biased result. The examples run on Node.js 24.

The Fisher-Yates shuffle

JavaScript
function shuffle(array, random = Math.random) {
  const result = [...array];

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

  return result;
}

const deck = [1, 2, 3, 4, 5, 6, 7, 8];
const shuffled = shuffle(deck);

console.log(shuffled.length, shuffled.toSorted((a, b) => a - b).join(" "));
console.log(deck.join(" "));
console.log(shuffle([]), shuffle([9]));
Text
8 1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
[] [ 9 ]

The function copies the input, so the original array is not changed, and then goes from the last position down to the second. At each position i it picks a random index j from 0 to i, inclusive, and swaps the two items. The random order of the output cannot be shown, since it changes each run, so the printed lines check what must be true: the result has the same eight items, the original is untouched, and the edge cases of an empty array and a single item work. Each item is placed exactly once, and each of the n! orders has the same probability, which is the property a fair shuffle needs.

A seeded generator for exact output

To show real shuffles and to test them, we replace Math.random with a small deterministic generator, mulberry32, that returns the same sequence for the same seed. The function is a few lines and is widely used for tests and games.

JavaScript
function mulberry32(seed) {
  return function () {
    seed |= 0;
    seed = (seed + 0x6d2b79f5) | 0;
    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

const random = mulberry32(42);
console.log(random(), random());

console.log(shuffle([1, 2, 3, 4, 5, 6, 7, 8], mulberry32(42)).join(" "));
console.log(shuffle([1, 2, 3, 4, 5, 6, 7, 8], mulberry32(42)).join(" "));
console.log(shuffle(["a", "b", "c", "d", "e"], mulberry32(2026)));
Text
0.6011037519201636 0.44829055899754167
3 8 2 1 7 6 4 5
3 8 2 1 7 6 4 5
[ 'a', 'e', 'd', 'b', 'c' ]

The same seed gives the same shuffle every time, which is what makes a seeded generator useful for reproducible tests, for replaying a game and for debugging. This generator is not secure and not suitable for anything where unpredictability matters. It is here so the examples have exact output, and Math.random is the default for ordinary use.

Proof by counting: the correct shuffle is uniform

For three items there are six possible orders. If a shuffle is fair, each should come up about one sixth of the time over many runs. This counts the outcomes of 6,000 shuffles of [1, 2, 3], with a fixed seed so the numbers are exact.

JavaScript
function countOutcomes(shuffleFn, runs = 6000) {
  const random = mulberry32(7);
  const counts = new Map();
  for (let run = 0; run < runs; run++) {
    const key = shuffleFn([1, 2, 3], random).join("-");
    counts.set(key, (counts.get(key) ?? 0) + 1);
  }
  return [...counts].sort().map(([order, count]) => `${order} ${count}`).join("\n");
}

console.log(countOutcomes(shuffle));
Text
1-2-3 945
1-3-2 1023
2-1-3 1021
2-3-1 999
3-1-2 1000
3-2-1 1012

Each order appears close to the expected 1,000 times, and the differences are the ordinary noise of random sampling. This is the evidence that Fisher-Yates is uniform. A count like this is also the standard way to test any shuffle you write: run it many times on a small array and look at the spread.

A plausible variant that is biased

The most common mistake is a shuffle that swaps every position with a random position anywhere in the array.

JavaScript
function naiveShuffle(array, random = Math.random) {
  const result = [...array];

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

  return result;
}

console.log(countOutcomes(naiveShuffle));
Text
1-2-3 883
1-3-2 1155
2-1-3 1078
2-3-1 1140
3-1-2 875
3-2-1 869

This looks as random as the correct one, and the counts are visibly uneven: 1-3-2 and 2-3-1 appear more than 1,100 times, and 3-2-1 fewer than 870. The cause is arithmetic. With three items and three swaps, each of which has three choices, there are 27 equally likely sequences of swaps, and 27 cannot be divided evenly among 6 outcomes, so some orders must come up more often. Fisher-Yates avoids this by shrinking the range at each step, so the number of paths is 3 × 2 × 1 = 6, one for each order. The difference is subtle, and it is why the algorithm has a name.

Why sort with Math.random fails

JavaScript
const check = mulberry32(42);
const compare = () => check() - 0.5;

console.log([Math.sign(compare()), Math.sign(compare())]);
Text
[ 1, -1 ]

A comparison function must be consistent: if it says that a sorts after b, it must say so every time, and the opposite for (b, a). This comparator answers the same question with different answers, here positive and then negative, since it returns a new random number each time. The specification says that sorting with an inconsistent comparator gives an implementation-defined result, so the order depends on the algorithm the engine uses, which can change between versions. Engines sort short arrays by insertion, and that makes some orders much more likely than others, with the exact bias depending on the engine and the length. It is also slow, since a sort does n log n comparisons where the shuffle does n swaps. There is no way to repair the idea, and we do not use it, even in code that does not matter.

Sampling a few items

To pick k random items without shuffling the whole array, stop the algorithm after k steps.

JavaScript
function sample(array, count, random = Math.random) {
  const result = [...array];
  const limit = Math.min(count, result.length);

  for (let i = 0; i < limit; i++) {
    const j = i + Math.floor(random() * (result.length - i));
    [result[i], result[j]] = [result[j], result[i]];
  }

  return result.slice(0, limit);
}

const pool = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

console.log(sample(pool, 3, mulberry32(5)));
console.log(sample(pool, 20, mulberry32(5)).length, sample([], 3));
Text
[ 7, 8, 4 ]
10 []

This version works from the front: at step i it chooses an item from the positions i to the end and moves it to position i, so the first k positions hold a uniform random sample without repeats. It does k steps and not n. Asking for more items than exist returns all of them, shuffled. Use it for picking winners, test data and random questions.

Secure randomness

Math.random() is fast and good enough for games, animations and test data, and it is not suitable when someone has a reason to predict the result: a raffle with a prize, a card game for money, a token, or a password. Use Node's crypto module, or crypto.getRandomValues in a browser.

JavaScript
import { randomInt } from "node:crypto";

function secureShuffle(array) {
  const result = [...array];
  for (let i = result.length - 1; i > 0; i--) {
    const j = randomInt(i + 1);
    [result[i], result[j]] = [result[j], result[i]];
  }
  return result;
}

console.log(Array.from({ length: 1000 }, () => randomInt(10)).every((n) => Number.isInteger(n) && n >= 0 && n < 10));
console.log(secureShuffle([1, 2, 3, 4, 5]).toSorted((a, b) => a - b).join(" "));
Text
true
1 2 3 4 5

randomInt(max) returns an unbiased integer from 0 up to but not including max, using a secure source. It avoids a trap of its own: taking a random 32-bit number and reducing it with % n favors small results whenever n does not divide 2 to the power 32 evenly, and randomInt rejects the values that would cause the bias. The shuffle is otherwise the same. The output order is random, so the example prints a sorted copy to show that all items are present.

A mistake we hit: swapping with the wrong range

JavaScript
function sattolo(array, random = Math.random) {
  const result = [...array];
  for (let i = result.length - 1; i > 0; i--) {
    const j = Math.floor(random() * i);
    [result[i], result[j]] = [result[j], result[i]];
  }
  return result;
}

const orders = new Set();
const random2 = mulberry32(3);
for (let run = 0; run < 500; run++) orders.add(sattolo([1, 2, 3], random2).join("-"));

console.log([...orders].sort());
console.log(sattolo([1, 2, 3, 4, 5], mulberry32(1)).every((value, index) => value !== index + 1));
Text
[ '2-3-1', '3-1-2' ]
true

An off-by-one in the range, random() * i instead of random() * (i + 1), never lets an item stay in place. That algorithm is real and named after Sattolo: it produces only cyclic permutations, so for three items it can make just two of the six orders, as the set shows, and no item ever ends at its original position. We shipped it in a "secret santa" tool and nobody noticed until a user pointed out that the results never repeated and that nobody ever drew themselves, which is correct for secret santa and wrong for a shuffle. Count the outcomes of any shuffle you write.

Choosing between the methods

You wantUse
A fair shuffle of a listFisher-Yates, as in shuffle() above
A shuffled copy, leaving the originalCopy first with [...array]
A few random itemsA partial Fisher-Yates, sample()
Reproducible output for testsA seeded generator such as mulberry32
Unpredictable results, such as a rafflecrypto.randomInt in place of Math.random
Neverarray.sort(() => Math.random() - 0.5)

Practical rules we follow

Use Fisher-Yates and nothing else. Count outcomes on a three-item array to test it. Copy the input unless the caller asked for in-place. Inject the random function so tests can be exact. Use crypto when the result matters to someone's money or security. Do not reduce random numbers with % unless the range divides evenly. And do not trust a shuffle because the output looks random.

Where this algorithm stops

Fisher-Yates is uniform only if the random source is, and Math.random has a limited internal state, so for very long arrays, not every one of the n! orders can be produced, though this matters in practice only for arrays of a few dozen items or more and for security uses. A shuffle does not guarantee that adjacent items differ, so a "random playlist" that must avoid repeats of an artist needs extra logic. The reference is in the Wikipedia article on the Fisher-Yates shuffle and the Node.js crypto.randomInt documentation.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.