Shuffle
VerifiedReturns a uniformly shuffled copy of an array (Fisher–Yates) without mutating it.
- array
- shuffle
- random
Install
npx shadcn@latest add https://quicksnip.dev/r/shuffle.jsonCode
/** Returns a new, uniformly shuffled copy of an array (Fisher–Yates). The input is not mutated. */
export function shuffle<T>(items: readonly T[], random: () => number = Math.random): T[] {
const result = [...items];
for (let i = result.length - 1; i > 0; i--) {
const j = Math.floor(random() * (i + 1));
[result[i], result[j]] = [result[j], result[i]];
}
return result;
}Usage
shuffle([1, 2, 3, 4, 5]); // e.g. [3, 5, 1, 4, 2]