Aller au contenu principal

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"