Skip to content

sample

Picks one or more random elements from an array. When called without a count, returns a single element or undefined if the array is empty. When called with a count, returns an array of up to count random elements sampled without replacement.

Available since v2.0.0

import { sample } from '@helpers4/array';
sample<T>(array: readonly T[] | null | undefined): T | undefined
ParameterTypeDescription
arrayreadonly T[] | null | undefinedThe source array to pick from

T | undefined — A single random element (or undefined) when no count is given, or an array of random elements when count is given

Without a count, returns one random element from the array.

sample([1, 2, 3, 4, 5])
// => 3 (random element)

With a count, returns an array of random elements sampled without replacement.

sample([1, 2, 3, 4, 5], 3)
// => [2, 5, 1] (3 random elements, without replacement)

Returns undefined when sampling from an empty array.

sample([])
// => undefined

View source on GitHub