Shuffle an array (Fisher-Yates)

The Fisher-Yates (Knuth) shuffle walks the array from the end and swaps each element with a random element at or before it, producing every permutation with equal probability in O(n) time; the popular sort(() => Math.random() - 0.5) is biased and should not be used.

Algorithm

for i from n-1 down to 1:
  j = random integer in [0, i]   // inclusive!
  swap arr[i], arr[j]

The +1 in Math.floor(Math.random() * (i + 1)) is essential; picking from [0, i) (Sattolo's algorithm) only produces cyclic permutations.

Why the sort trick is wrong

Sorting algorithms assume a consistent comparator. A random comparator gives a biased distribution (some orders come up much more often than others, and the bias depends on the engine's sort algorithm), and it is O(n log n) instead of O(n).

Randomness quality

  • Math.random() is fine for UI (shuffling cards in a game, randomising quiz questions).
  • For anything security-sensitive or fairness-critical (lotteries, raffles, cryptography), use crypto.getRandomValues and avoid modulo bias.

Practical notes

  • Shuffle a copy if the caller's array must not change.
  • For a random sample of k items, run only k iterations of the loop (a partial Fisher-Yates).
  • For reproducible shuffles (tests, seeded games), use a seeded pseudo-random generator.

Code example

js
1function shuffle(input, random = Math.random) {
2 const arr = [...input]; // shuffle a copy
3 for (let i = arr.length - 1; i > 0; i--) {
4 const j = Math.floor(random() * (i + 1)); // 0..i inclusive
5 [arr[i], arr[j]] = [arr[j], arr[i]];
6 }
7 return arr;
8}
9
10// Secure randomness for fairness-critical use
11const secureRandom = () => crypto.getRandomValues(new Uint32Array(1))[0] / 2 ** 32;
12
13console.log(shuffle([1, 2, 3, 4, 5]).length, shuffle(["a", "b", "c"], secureRandom).toSorted().join()); // 5 a,b,c
14
15// Verify uniformity: each of the 6 orders of [1,2,3] should appear ~1/6 of the time
16function distribution(shuffler, runs = 60_000) {
17 const counts = {};
18 for (let i = 0; i < runs; i++) {
19 const key = shuffler([1, 2, 3]).join("");
20 counts[key] = (counts[key] ?? 0) + 1;
21 }
22 const values = Object.values(counts);
23 return { orders: values.length, maxDeviation: Math.max(...values.map((v) => Math.abs(v / runs - 1 / 6))).toFixed(3) };
24}
25console.log("Fisher-Yates:", distribution(shuffle)); // { orders: 6, maxDeviation: ~0.00x } - uniform
26console.log("sort trick: ", distribution((a) => [...a].sort(() => Math.random() - 0.5))); // noticeably larger deviation - biased
27
28// Random sample of k items: partial Fisher-Yates
29function sample(input, k) {
30 const arr = [...input];
31 for (let i = 0; i < k; i++) {
32 const j = i + Math.floor(Math.random() * (arr.length - i));
33 [arr[i], arr[j]] = [arr[j], arr[i]];
34 }
35 return arr.slice(0, k);
36}
37console.log(sample(["a", "b", "c", "d", "e"], 2).length); // 2

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app