# Get random items of an array

Return count distinct items in random order.

Canonical: https://1loc.dev/random/get-random-items-of-an-array/
Version: 1.0.0
Runtime: JavaScript · Node.js 22 / modern browsers
Verification: Usage lines executed in Node.js 22 and headless Chromium; no external services
Updated: 2026-10-28

## Implementation

```javascript
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

```javascript
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.

## 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 does not validate its arguments. Add checks where it receives untrusted input.

## Source and license

Original: https://github.com/phuocng/1loc/blob/14b481cf60dff1620ab1bb99a43b1f68068cdd9b/contents/get-random-items-of-an-array.mdx
Author: Nguyen Huu Phuoc and original contributors
Contributors: See original repository history
Source commit: 14b481cf60dff1620ab1bb99a43b1f68068cdd9b
Copyright (c) 2020 phuoc-ng
License: MIT — https://1loc.dev/licenses/
Maintainer: Oveyon
Modifications: 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.
