Skip to content
jshacks.dev
Fundamentals

Shuffle an array with Fisher-Yates

Shuffle an array without bias using the Fisher-Yates algorithm, and compare it with the sort and random comparator shortcut over 60,000 runs. Node.js 24.

2 min read
Summarize in AI

array.sort(() => Math.random() - 0.5) is the most copied shuffle on the internet, and it does not produce an even shuffle. The Fisher-Yates version is a few lines longer and does.

JavaScript
function shuffle(items, random = Math.random) {
  const copy = [...items];
  for (let i = copy.length - 1; i > 0; i--) {
    const j = Math.floor(random() * (i + 1));
    [copy[i], copy[j]] = [copy[j], copy[i]];
  }
  return copy;
}

function mulberry32(seed) {
  return () => {
    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;
  };
}

console.log(shuffle([1, 2, 3, 4, 5], mulberry32(7)));

function tally(method) {
  const random = mulberry32(1);
  const seen = {};
  for (let i = 0; i < 60000; i++) {
    const key = method(random).join('');
    seen[key] = (seen[key] ?? 0) + 1;
  }
  return Object.entries(seen).sort(([a], [b]) => a.localeCompare(b));
}

console.log(tally((random) => shuffle([1, 2, 3], random)));
console.log(tally((random) => [1, 2, 3].sort(() => random() - 0.5)));
Text
[ 4, 2, 3, 5, 1 ]
[
  [ '123', 9948 ],
  [ '132', 9888 ],
  [ '213', 10069 ],
  [ '231', 10000 ],
  [ '312', 10116 ],
  [ '321', 9979 ]
]
[
  [ '123', 22381 ],
  [ '132', 3779 ],
  [ '213', 7557 ],
  [ '231', 3816 ],
  [ '312', 3676 ],
  [ '321', 18791 ]
]

The function walks the array from the end and swaps each item with a random earlier one, or itself. To make the check repeatable, the example drives both versions with a seeded generator and counts how often each of the six orders of three items appears in 60,000 shuffles. Fisher-Yates lands between 9,888 and 10,116 times on each, close to 10,000. The sort version returned 123 22,381 times and 321 18,791 times, and the other four orders between 3,676 and 7,557, so the original order survives in 37 percent of the runs. A comparator that answers randomly breaks the contract of Array.prototype.sort, which is why the result depends on the engine's algorithm.

These counts are from Node.js 24 and V8's sort, and another engine can give a different bias. Fisher-Yates is correct whatever the engine. The function copies the array, so the input is not changed. The generator is a parameter, and for a shuffle that must not be predictable pass one built on crypto.getRandomValues.

Share

More snippets

Fundamentals

Sort dates in an array

Sort an array of Date objects by subtracting them, and see why the default sort orders dates by weekday name. Works in every Node.js release.

1 min read
Fundamentals

Sort by multiple keys

Sort records by several keys in one comparator with toSorted, falling through to the next key when the first ties. Needs Node.js 20, stable since ES2019.

1 min read
Fundamentals

Get a random item from an array

Pick a random item from an array with Math.random, and see why rounding the index instead of flooring it makes the middle item twice as likely. Node.js 18.

2 min read

Get new posts by email

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

Unsubscribe in one click. No spam, ever.