JavaScript

Shuffle Array (Fisher-Yates)

by @admin
10h ago
Apr 28, 2026
Public
Randomly shuffles an array in-place using the Fisher-Yates algorithm, which produces a uniformly random permutation. Widely considered the correct way to shuffle — avoids the bias inherent in sort(() => Math.random() - 0.5). Returns the same array reference after shuffling.
JavaScript
function shuffle(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}

// Non-mutating version
const shuffled = (arr) => shuffle([...arr]);

// Usage
console.log(shuffled([1, 2, 3, 4, 5])); // e.g. [3, 1, 5, 2, 4]
Tags

Save your own code snippets

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