Emmanuel Akinfulubi

JavaScriptBasic

Shuffle an array randomly (Fisher-Yates) in JavaScript

Advanced · 4 min read

Shuffling puts a list in random order. Card games, quiz apps that mix up their questions, playlists on shuffle and "random pick of the day" features all need it. There is a famous one-line shuffle that you will find everywhere, and it is quietly unfair: some orders come up far more often than others.

In this tutorial you will write shuffle(values) using the Fisher-Yates algorithm, which gives every possible order exactly the same chance. Then you will measure the popular one-liner and see its bias in numbers. You need to know what an array, a loop and a function are. Random numbers are explained below.

Random whole numbers

Math.random() gives a random decimal from 0 up to, but not including, 1. To pick a random position in a list, you scale it and round down:

JavaScript

const i = Math.floor(Math.random() * 5);
console.log(i); // one of 0, 1, 2, 3 or 4, different each run

Math.random() * 5 is somewhere from 0 up to (but not including) 5. Math.floor rounds down to a whole number, so you get 0, 1, 2, 3 or 4, each equally likely.

What "fair" means

A list of 3 items can be arranged in 6 orders: 3 × 2 × 1. A fair shuffle gives each of those 6 orders the same chance. A simpler test that follows from it: any given item should end up in any given position equally often. With 10 items, the item that started first should still be first in about 1 shuffle out of 10.

Here is the exercise. Try it yourself first if you like, or follow the steps.

36 Shuffle an array fairly

hard

Put an array in random order. Use a shuffle that is actually uniform, and show why the popular one-liner is not.

Stuck? Three hints, smallest first
  1. 1. sort(() => Math.random() - 0.5) is the popular version and it is biased.
  2. 2. Fisher-Yates walks from the end, swapping each element with a random earlier one.
  3. 3. Test a shuffle by running it many times and checking the distribution, not by looking at one result.

Step 1: the one-liner and why it's wrong

This is the version you will see most:

Step 1

const badShuffle = (values) => [...values].sort(() => Math.random() - 0.5);
console.log(badShuffle([1, 2, 3, 4, 5])); // some order, different each run

sort asks its function to compare two items, and a negative or positive answer decides which goes first. Here the answer is random. The result looks shuffled, but sort assumes its answers are consistent: if it says a comes before b once, it will say so again. Random answers break that assumption. Which orders come out more often then depends on the sorting method the JavaScript engine happens to use. Step 5 measures the damage.

Step 2: the idea behind Fisher-Yates

Think of drawing names out of a hat. You pick one at random and put it in the last seat. Then you pick one of the remaining names for the second-to-last seat, and so on, until the hat is empty. Every name had a fair chance at every seat.

Fisher-Yates does this inside the array. Walk backwards from the last position. At each position i, pick a random position j from 0 to i (the part not yet "seated"), and swap the two items.

Step 3: write it

Step 3

function shuffle(values) {
  const out = [...values];
  for (let i = out.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [out[i], out[j]] = [out[j], out[i]];
  }
  return out;
}
console.log(shuffle([1, 2, 3, 4, 5])); // some order, different each run

Line by line:

  • [...values] copies the array, so the caller's list is left alone.
  • The loop starts at the last position and stops before position 0. By then only one item is left, so there is nothing to choose.
  • Math.random() * (i + 1) gives a position from 0 to i, including i. Letting an item stay where it is matters: without that, some orders could never happen.
  • [out[i], out[j]] = [out[j], out[i]] swaps the two items using destructuring.

Step 4: check nothing was lost

A shuffle must keep every item exactly once. Sort the result back into order and compare:

JavaScript

const result = shuffle([1, 2, 3, 4, 5]);
console.log([...result].sort((a, b) => a - b)); // [ 1, 2, 3, 4, 5 ]
const original = [1, 2, 3];
shuffle(original);
console.log(original); // [ 1, 2, 3 ]: unchanged
console.log(shuffle([]), shuffle([9])); // [] [ 9 ]

Empty and single-item lists work too, because the loop simply doesn't run.

Step 5: measure the bias

You can't judge a shuffle by looking at one result. Every order is possible, so any single result looks fine. Instead, run it thousands of times and count. Here we shuffle a list of 10 items 20,000 times and count how often the item 1 stays first. A fair shuffle should manage about 10%.

JavaScript

const TEN = Array.from({ length: 10 }, (_, i) => i + 1);
function firstStaysFirst(fn) {
  let count = 0;
  for (let i = 0; i < 20000; i++) if (fn(TEN)[0] === 1) count++;
  return count / 20000;
}
console.log((firstStaysFirst(shuffle) * 100).toFixed(1) + '%');    // about 10%
console.log((firstStaysFirst(badShuffle) * 100).toFixed(1) + '%'); // far more, often about double

Array.from({ length: 10 }, (_, i) => i + 1) builds [1, 2, ..., 10]. toFixed(1) rounds to one decimal place for printing. The exact numbers change on every run, since they are random, but the gap between the two doesn't go away. The full solution also checks every position, not just the first.

The full solution

The complete answer has shuffle and the one-liner, checks that the shuffle keeps every item and leaves the original untouched, then measures both versions over 20,000 runs and compares them. Press Run to see the output, and press it again to see the numbers change while the gap stays.

The answer

// Fisher-Yates. Walk backwards, swap with a random index at or before i.
function shuffle(values) {
  const out = [...values];
  for (let i = out.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [out[i], out[j]] = [out[j], out[i]];
  }
  return out;
}

// The popular one-liner. Looks fine, is not uniform.
const badShuffle = (values) => [...values].sort(() => Math.random() - 0.5);

console.log('shuffled:', shuffle([1, 2, 3, 4, 5]).join(', '));

/* Measuring the bias needs care. With five elements the sort version is only a
   few points off, which hides in the noise of a few thousand runs. With TEN it
   keeps the first element first about twice as often as it should, which is
   unmistakable. So the measurement uses ten. */
const TEN = Array.from({ length: 10 }, (_, i) => i + 1);
const RUNS = 20000;

function firstStaysFirst(fn) {
  let count = 0;
  for (let i = 0; i < RUNS; i++) if (fn(TEN)[0] === 1) count++;
  return count / RUNS;
}

// Stronger still: where does element 1 land? Every position should be 1 in 10.
function positionSpread(fn) {
  const seen = Array(10).fill(0);
  for (let i = 0; i < RUNS; i++) seen[fn(TEN).indexOf(1)]++;
  return Math.max(...seen.map((n) => Math.abs(n / RUNS - 0.1)));
}

const fair = firstStaysFirst(shuffle);
const biased = firstStaysFirst(badShuffle);
const fairSpread = positionSpread(shuffle);
const biasedSpread = positionSpread(badShuffle);

console.log('with ten elements, every position should be 10.0%');
console.log('fair shuffle keeps 1 first', (fair * 100).toFixed(1) + '% of the time');
console.log('sort shuffle keeps 1 first', (biased * 100).toFixed(1) + '% of the time  <- about double');
console.log('worst position error, fair:', (fairSpread * 100).toFixed(1) + ' points');
console.log('worst position error, sort:', (biasedSpread * 100).toFixed(1) + ' points');

Output


      
11 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 11 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

11 checks

test('the shuffle keeps every element', shuffle([1, 2, 3, 4, 5]).sort((a, b) => a - b), [1, 2, 3, 4, 5]);
test('and the same length', shuffle([1, 2, 3]).length, 3);
test('the original is untouched', (() => { const a = [1, 2, 3]; shuffle(a); return a; })(), [1, 2, 3]);
test('a single element is fine', shuffle([9]), [9]);
test('an empty array is fine', shuffle([]), []);
test('the fair shuffle leaves 1 first about a tenth of the time', Math.abs(fair - 0.1) < 0.02, true);
test('the sort version does it far too often', biased > 0.15, true);
test('roughly twice as often as it should', biased / fair > 1.5, true);
test('every position is near even for the fair shuffle', fairSpread < 0.02, true);
test('and badly uneven for the sort one', biasedSpread > 0.05, true);
test('so the sort version is off by an order of magnitude more', biasedSpread / fairSpread > 5, true);

The measurement is the exercise. With ten elements a uniform shuffle leaves the first element in place one time in ten; the sort one-liner leaves it there about twice as often, and the assertions check both the rate and the spread across every position.

The reason is that sort assumes its comparator is consistent — if it says a comes before b once, it will say so again. A comparator returning random values breaks that assumption, so the outcome depends on which algorithm the engine happens to use and which elements it happens to compare. It is not merely imperfect; it is undefined behaviour that looks like it works. Fisher-Yates is five lines and provably uniform.

Worth noting how easy this was to under-test. An earlier version of this exercise measured five elements, where the bias is only a few points — small enough that it passed or failed depending on the run. Ten makes it unmistakable. When testing a statistical claim, pick the case where the effect is large, and assert a ratio rather than a narrow threshold.

Common mistakes

  • Using sort(() => Math.random() - 0.5). It looks random and isn't fair. Use Fisher-Yates.
  • Picking j from the whole array every time. Choosing from 0 to the last position at every step, instead of 0 to i, also gives a biased result.
  • Shuffling the caller's array in place by accident. Copy first with [...values] unless changing the original is what you want.

Try it yourself

  1. Write pickRandom(values) that returns one random item from an array.
  2. Write sample(values, n) that returns n different random items. (Hint: shuffle and take the first n with slice.)
  3. Shuffle ['a', 'b', 'c'] 60,000 times and count how often each of the 6 orders appears. Each should be close to 10,000.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.