Shuffle an array
Return a new array in random order, every order equally likely.
function shuffle(values) {
const result = [...values];
for (let i = result.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[result[i], result[j]] = [result[j], result[i]];
}
return result;
}
Usage
const deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
shuffle(deck).toSorted((a, b) => a - b); // → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
deck; // → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
shuffle(deck); // e.g. [9, 1, 10, 6, 8, 5, 2, 3, 7, 4]
Know the limits
- Fisher–Yates in O(n). The original sorted by random keys, which is also unbiased but O(n log n); avoid sort(() => Math.random() - 0.5), which is biased.
- Math.random is not cryptographic. For draws people could dispute, use crypto.getRandomValues, as in Generate a random string from given characters.
- The input array is unchanged.
The function above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.
Source & maintenance
Based on Shuffle an array from the original 1loc collection by Nguyen Huu Phuoc, with elkarouani. Copyright (c) 2020 phuoc-ng. MIT licensed.
Fisher–Yates in O(n) instead of sorting by random keys. Documented as a reference with executed usage lines. Original MDX retained as inert source evidence.
Maintained by Oveyon. Original source commit: 14b481cf60df. This edition’s file: contents/shuffle-an-array.mdx in akamind/1loc, commit 0a77f131b22d. Read the license.
Keep exploring
- Clone an array — Create a new array without copying the objects inside it.
- Remove duplicate values — Keep the first occurrence of each value, in its original order.
- Flatten a nested array — Turn a nested array into one sequence of values.