Get a random item and remove it from an array
Remove one random item from the array and return it.
function takeRandomItem(values) { return values.splice(Math.floor(Math.random() * values.length), 1)[0]; }
Usage
const pool = ['ana', 'rui', 'lia'];
const picked = takeRandomItem(pool);
pool.length; // → 2
pool.includes(picked); // → false
takeRandomItem([]); // → undefined
Know the limits
- Mutates the array. The original returned the one-item array from splice, such as [7], not the item; [0] unwraps it.
- Removing from the middle is O(n). To draw many items, shuffle once and pop.
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 a random item and remove it from an array from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Returns the item; the original returned a one-item array. 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/get-a-random-item-and-remove-it-from-an-array.mdx in akamind/1loc, commit 0a77f131b22d. 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.