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>
);
Select a random featured item for homepageβ
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);