How do you randomly shuffle an array in JavaScript using the Fisher-Yates algorithm? | A1Lab@FahadM to JavaScriptEnglish • 4 days ago

How do you randomly shuffle an array in JavaScript using the Fisher-Yates algorithm?

message-square
0

To randomly shuffle an array in JavaScript using the Fisher-Yates algorithm (also known as the Knuth shuffle), iterate backward from the last index i = arr.length - 1 down to 1, pick a uniformly random index j in the inclusive range 0 <= j <= i (Math.floor(Math.random() * (i + 1))), and swap arr[i] with arr[j]. To keep the code non-mutating and safe for callers, copy the input array first ([...items]) before performing the in-place swaps on the copy.


1. Non-Mutating Fisher-Yates Shuffle on a Copied Array

Clone the input array into a fresh array (const copy = [...items]) and run the backward swap loop from copy.length - 1 down to 1 so the original array remains intact while every permutation is produced with uniform probability:

// Return a newly shuffled copy of an array using Fisher-Yates without mutating input
function shuffleArray(items, rng = Math.random) {
  if (!Array.isArray(items)) {
    throw new TypeError("Expected an array to shuffle.");
  }

  const randomFn = typeof rng === "function" ? rng : Math.random;
  const copy = [...items];

  for (let i = copy.length - 1; i > 0; i -= 1) {
    const rawRandom = randomFn();
    const clampedRandom =
      typeof rawRandom === "number" && Number.isFinite(rawRandom)
        ? Math.min(Math.max(rawRandom, 0), 0.9999999999999999)
        : Math.random();
    const j = Math.floor(clampedRandom * (i + 1));

    const temp = copy[i];
    copy[i] = copy[j];
    copy[j] = temp;
  }

  return copy;
}

// Example usage:
const deck = ["A", "K", "Q", "J"];
const shuffled = shuffleArray(deck);
console.log("Shuffled:", shuffled);
console.log("Original untouched:", deck); // ["A", "K", "Q", "J"]
  • Uniform $O(n)$ shuffle: Swaps each position i with a random index j from 0 to i in a single pass.
  • Non-mutating by default: Copies items via [...items] so caller arrays are never unexpectedly reordered.

2. Customizing Randomness or Generating Deterministic Shuffles

Accepting an injectable rng function makes it easy to pass a custom pseudo-random number generator (PRNG) for repeatable tests or simulations while keeping input guards and array immutability intact:

// Create a deterministic seeded PRNG (Mulberry32) for repeatable Fisher-Yates runs
function createSeededRng(seed = 1) {
  let state = (Number(seed) >>> 0) || 1;
  return () => {
    state = (state + 0x6d2b79f5) >>> 0;
    let t = Math.imul(state ^ (state >>> 15), 1 | state);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

// Example usage:
const seededRandom = createSeededRng(20261128);
console.log(shuffleArray([1, 2, 3, 4, 5], seededRandom));
  • Injectable rng hook: Lets tests pass deterministic generators without mutating global Math.random.
  • Clamped [0, 1) output: Protects Math.floor(rand * (i + 1)) against out-of-range random values.

3. Common Traps to Avoid

Implementing or replacing the Fisher-Yates shuffle in JavaScript often runs into a few pitfalls:

  • Using items.sort(() => Math.random() - 0.5) instead of Fisher-Yates: Comparator sorting with random numbers is biased—different array engines and element counts produce uneven distributions and can even ignore transitivity assumptions.
  • Picking j across 0 to arr.length - 1 on every step instead of 0 to i: Sampling outside 0 <= j <= i breaks the uniform permutation math of the Fisher-Yates algorithm.
  • Mutating a shared caller array unintentionally: Shuffling an array passed from state or props in place can cause subtle UI or reference bugs—prefer shuffling a copy ([...items]).

TL;DR: Copy the array (const copy = [...items]) and loop i from copy.length - 1 down to 1, swapping copy[i] with copy[Math.floor(Math.random() * (i + 1))] for an unbiased, non-mutating Fisher-Yates shuffle.