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
Section titled “Import”Signature
Section titled “Signature”Parameters
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
array | readonly T[] | null | undefined | The source array to pick from |
Returns
Section titled “Returns”T | undefined — A single random element (or undefined) when no count is given, or an array of random elements when count is given
Examples
Section titled “Examples”Pick a single random element
Section titled “Pick a single random element”Without a count, returns one random element from the array.
Pick multiple random elements
Section titled “Pick multiple random elements”With a count, returns an array of random elements sampled without replacement.
Empty array returns undefined
Section titled “Empty array returns undefined”Returns undefined when sampling from an empty array.
