TypeScript

Shuffle (Fisher-Yates)

admin by @admin ADMIN
Jun 19, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Uniformly shuffle an array in place using the modern Fisher-Yates algorithm. Returns the same array for chaining. Use crypto.getRandomValues for cryptographic uses.
TypeScript
Raw
export function shuffle<T>(arr: T[]): T[] {
  for (let i = arr.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [arr[i], arr[j]] = [arr[j]!, arr[i]!];
  }
  return arr;
}

// Cryptographically secure variant:
export function shuffleCrypto<T>(arr: T[]): T[] {
  const buf = new Uint32Array(1);
  for (let i = arr.length - 1; i > 0; i--) {
    crypto.getRandomValues(buf);
    const j = buf[0]! % (i + 1);
    [arr[i], arr[j]] = [arr[j]!, arr[i]!];
  }
  return arr;
}

shuffle([1, 2, 3, 4, 5]);   // e.g. [4, 1, 5, 3, 2]
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.