Get random items of an array
Return count distinct items in random order.
function randomItems(values, count) {
const pool = [...values];
for (let i = pool.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[pool[i], pool[j]] = [pool[j], pool[i]];
}
return pool.slice(0, count);
}
Usage
const picks = randomItems([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 8);
picks.length; // → 8
new Set(picks).size; // → 8
randomItems(['a', 'b'], 5).length; // → 2
Know the limits
- The original spliced the array that reduce was walking, so reduce skipped the removed positions: asking for 8 of 10 items returned 5.
- Items are distinct by position. Asking for more items than exist returns all of them, shuffled.
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 Get random items of an array from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Shuffles a copy and slices; the original returned fewer items than requested when asked for more than half. Documented as a reference with executed usage lines. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Generate a random boolean — Return true or false with equal probability.
- Generate a random floating point number in given range — Scale Math.random into [min, max).
- Generate a random hex color — Return a #rrggbb color from 24 random bits.