Skip to main content

sample()

sample<T>(array): T | undefined

Gets a random element from an array.


Type Parametersโ€‹

T: Tโ€‹

The type of elements in the array.


Parametersโ€‹

array: readonly T[]โ€‹

The array to sample from.


Returns: T | undefinedโ€‹

A random element, or undefined if the array is empty.


Sinceโ€‹

2.0.0


Performanceโ€‹

O(1) time & space, direct index access with early return for empty arrays.


Also known asโ€‹

draw (Radashi) ยท randomElem (Modern Dash) ยท sample (Lodash, es-toolkit, Remeda, Antfu) ยท โŒ (Ramda, Effect)


Exampleโ€‹

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

sample([{ name: 'John' }, { name: 'Jane' }]);
// => { name: 'Jane' } (random)

How it works?โ€‹

Returns a random element from an array. O(1) operation โ€” direct index access.


Use Casesโ€‹

Pick a random winner from a contest ๐Ÿ“Œโ€‹

Select a lucky participant for prizes or rewards. Perfect for raffles, sweepstakes, or promotional campaigns.

const contestants = [
{ id: "P1", name: "Alice" },
{ id: "P2", name: "Bob" },
{ id: "P3", name: "Charlie" },
{ id: "P4", name: "Diana" },
];

const winner = sample(contestants);
// => { id: "P3", name: "Charlie" }

console.log(`๐ŸŽ‰ Congratulations ${winner?.name}!`);

Display a random tip or quoteโ€‹

Show dynamic content to keep users engaged. Ideal for onboarding screens, dashboards, or loading states.

const tips = [
"Break large tasks into smaller chunks.",
"Use keyboard shortcuts to speed up your workflow.",
"Take a 5-minute break every 25 minutes.",
"Start your day with the most challenging task.",
];

const dailyTip = sample(tips);
// => "Start your day with the most challenging task."

Assign A/B test variantsโ€‹

Randomly assign users to experiment groups. Useful for feature testing or split testing.

const variants = ["control", "variant-a", "variant-b"];

const assignedVariant = sample(variants);
// => "variant-b"