Get random items of an array

Return count distinct items in random order.

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

get-random-items-of-an-array.js
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

usage.js
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

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

  • 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.

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”.