Get a random item and remove it from an array

Remove one random item from the array and return it.

JavaScriptNode.js & browsers Version 1.0.0 · MIT · .md

get-a-random-item-and-remove-it-from-an-array.js
function takeRandomItem(values) { return values.splice(Math.floor(Math.random() * values.length), 1)[0]; }

Usage

usage.js
const pool = ['ana', 'rui', 'lia'];
const picked = takeRandomItem(pool);
pool.length; // → 2
pool.includes(picked); // → false
takeRandomItem([]); // → undefined

Lines marked → were executed in Node.js 22 and in headless Chromium, and each result was compared with the value shown. Lines marked e.g. are illustrative.

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.

Usage lines executed in Node.js 22 and headless Chromium; no external services · reviewed October 28, 2026.

Keep exploring

Type two or more characters. Try “duplicate”, “webhook” or “retry”.