← Back to JavaScript, page 9

javascript-0165 · Easy fresher

How do you shuffle an array correctly, and why is sort(() => Math.random() - 0.5) a bad idea?

Use the Fisher-Yates shuffle: walk from the end of the array, pick a random index from 0 to the current position, and swap, which gives every permutation the same probability in O(n) time. Sorting with a random comparator is biased and engine-dependent, because the comparator is inconsistent. For security uses such as tokens, use crypto.getRandomValues, not Math.random.

Full answer

A shuffle should make every possible order equally likely. For an array of n items there are n factorial orders.

Fisher-Yates: for i from n - 1 down to 1, choose a random integer j with 0 <= j <= i, and swap a[i] and a[j]. Each position is filled once, and each item has an equal chance to land in each place. It runs in O(n) time and O(1) extra space when shuffling in place. Copy the array first if the original must stay unchanged.

Random integers: Math.floor(Math.random() * (max + 1)) gives 0..max. The classic bug is using Math.round, which makes the first and last values half as likely, or using i + 1 incorrectly and producing a modulo or off-by-one bias. Another common mistake is choosing j from the whole array on every step (0..n-1), which looks right but is biased: it produces n to the power n equally likely paths that cannot map evenly onto n! orders.

Why array.sort(() => Math.random() - 0.5) is wrong: a comparator must be consistent (the same two items must always compare the same way). A random comparator breaks this rule, so the sort algorithm gets contradictory answers, and the result depends on the algorithm of the engine. Results are visibly biased: some items stay near their start position much more often than chance. It is also O(n log n) instead of O(n).

Sampling: to pick k random items without repeats, run only the first k steps of a Fisher-Yates shuffle, or shuffle a copy and take k. To pick one item: items[Math.floor(Math.random() * items.length)].

Security: Math.random is not cryptographically secure and cannot be seeded. For tokens, passwords, or a fair draw with money at stake, use crypto.getRandomValues (browsers and Node.js). For repeatable tests, use a seeded generator such as mulberry32 so the output is the same on every run.

javascript
// a small seeded generator, so the demonstration gives the same output on every run
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;
  };
}

function shuffle(items, random = Math.random) {
  const copy = items.slice();
  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 badShuffle(items, random) {
  const copy = items.slice();
  for (let i = 0; i < copy.length; i++) {
    const j = Math.floor(random() * copy.length); // wrong: chooses from the whole array
    [copy[i], copy[j]] = [copy[j], copy[i]];
  }
  return copy;
}

const sample = (items, k, random) => shuffle(items, random).slice(0, k);

// count how often each permutation of [1, 2, 3] appears in 60000 shuffles
function distribution(method, random) {
  const counts = {};
  for (let run = 0; run < 60000; run++) {
    const key = method([1, 2, 3], random).join('');
    counts[key] = (counts[key] ?? 0) + 1;
  }
  return Object.fromEntries(Object.entries(counts).sort());
}

const random = mulberry32(2026);
console.log('Fisher-Yates (about 10000 each):', distribution(shuffle, random));
console.log('wrong version (uneven):          ', distribution(badShuffle, random));
const biasedSort = (items, rnd) => items.slice().sort(() => rnd() - 0.5);
console.log('random comparator sort:          ', distribution(biasedSort, random));

const original = [1, 2, 3, 4, 5];
const mixed = shuffle(original, mulberry32(7));
console.log(original, mixed, 'same items:', [...mixed].sort().join() === original.join());
console.log('sample of 2:', sample(['a', 'b', 'c', 'd', 'e'], 2, mulberry32(3)));

const token = crypto.getRandomValues(new Uint8Array(8));
console.log('secure random bytes:', token.length, 'values in range:', [...token].every((b) => b >= 0 && b <= 255));
const randomInt = (min, max, rnd = Math.random) => Math.floor(rnd() * (max - min + 1)) + min;
console.log('dice rolls:', Array.from({ length: 8 }, () => randomInt(1, 6, mulberry32(11))).length, 'range ok:', randomInt(1, 6) >= 1 && randomInt(1, 6) <= 6);

Run with Node.js v24.22.1 as js-165.js; two runs gave identical output. Output: Fisher-Yates (about 10000 each): { '123': 9976, '132': 9934, '213': 10018, '231': 9914, '312': 10033, '321': 10125 } wrong version (uneven): { '123': 8951, '132': 11177, '213': 11037, '231': 11005, '312': 8866, '321': 8964 } random comparator sort: { '123': 22289, '132': 3766, '213': 7529, '231': 3794, '312': 3758, '321': 18864 } [ 1, 2, 3, 4, 5 ] [ 4, 2, 3, 5, 1 ] same items: true sample of 2: [ 'c', 'e' ] secure random bytes: 8 values in range: true dice rolls: 8 range ok: true

Key points

  • Fisher-Yates: loop from the end, swap with a random index from 0 to i; unbiased and O(n).
  • Use Math.floor(Math.random() * (i + 1)); avoid Math.round and choosing from the whole array each time.
  • A random sort comparator is inconsistent, so it is biased and engine-dependent.
  • Sampling k items means running k steps of the shuffle.
  • Use crypto.getRandomValues for security and a seeded generator for tests.

Common mistakes

  • Shuffling with sort(() => Math.random() - 0.5).
  • Choosing the swap index from the whole array in every step.
  • Using Math.round to build a random integer.
  • Using Math.random for tokens, passwords, or security decisions.

Follow-ups

  • Why does choosing from the whole array give n to the n paths, and why is that biased?
  • How would you pick a random item with weights?
  • How does crypto.getRandomValues differ from Math.random?

Tips

  • Name Fisher-Yates and describe it in one sentence.
  • Explain why the random comparator is invalid.
  • Say that you would test the fairness by counting permutations of a small array.