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."

Pick a random placeholder image​

Select a random placeholder when no image is available. Adds visual variety to empty states and fallback content.

const placeholders = [
"/img/placeholder-landscape.svg",
"/img/placeholder-abstract.svg",
"/img/placeholder-gradient.svg",
];

const fallbackImage = sample(placeholders);
// => "/img/placeholder-abstract.svg"

Pick a random loading message​

Show a different loading message each time to keep users engaged. Perfect for loading screens, splash pages, and progress indicators.

const loadingMessages = [
"Brewing your data...",
"Almost there...",
"Crunching the numbers...",
"Fetching the good stuff...",
"Warming up the servers...",
];

const LoadingScreen = () => (
<div className="loading">
<Spinner />
<p>{sample(loadingMessages)}</p>
</div>
);

Rotate featured content on the homepage without manual curation. Essential for marketplaces, blogs, and content platforms.

const featuredProducts = [
{ id: "p1", name: "Pro Headphones", image: "/img/headphones.jpg" },
{ id: "p2", name: "Smart Watch", image: "/img/watch.jpg" },
{ id: "p3", name: "Wireless Speaker", image: "/img/speaker.jpg" },
];

const spotlight = sample(featuredProducts);
renderHeroBanner(spotlight);