Skip to content

sample ​

The sample function returns a random element from an array.

Syntax ​

typescript
sample<T>(array: T[]): T | undefined;

Parameters ​

NameTypeDescription
arrayT[] | stringSource array or string

Returns ​

TypeDescription
T | string | undefinedRandom element or character, or undefined if empty

Examples ​

typescript
sample([1, 2, 3, 4]); // => 2 (example)
sample([]); // => undefined

Notes ​

  • Returns undefined if the array is empty.
  • Useful for obtaining random samples.

References ​

Released under the MIT License.