sampleSize()
sampleSize<
T>(array,n):T[]
Gets n random elements from an array.
Uses Fisher-Yates shuffle algorithm for unbiased sampling.
Type Parametersβ
T: Tβ
The type of elements in the array.
Parametersβ
array: readonly T[]β
The array to sample from.
n: numberβ
The number of elements to sample.
Returns: T[]β
A new array of sampled elements.
Throwsβ
RangeError If n is negative.
Sinceβ
2.0.0
Performanceβ
O(n) time & space for the shuffled copy.
Also known asβ
sample (Remeda) Β· sampleSize (Lodash, es-toolkit) Β· β (Radashi, Ramda, Effect, Modern Dash, Antfu)
Exampleβ
sampleSize([1, 2, 3, 4, 5], 3);
// => [3, 1, 5] (random)
sampleSize(['a', 'b', 'c'], 2);
// => ['b', 'a'] (random)
sampleSize([1, 2, 3], 5);
// => [2, 3, 1] (returns all if n > length)
How it works?β
Returns n random elements using partial Fisher-Yates shuffle.
Use Casesβ
Select multiple random items for testing πβ
Get N random elements from an array for sampling or testing. Perfect for generating test data, random selections, or batch sampling.
const products = [
{ id: 1, name: "Laptop" },
{ id: 2, name: "Phone" },
{ id: 3, name: "Tablet" },
{ id: 4, name: "Watch" },
{ id: 5, name: "Headphones" },
];
const testSample = sampleSize(products, 3);
// => [{ id: 3, name: "Tablet" }, { id: 1, name: "Laptop" }, { id: 5, name: "Headphones" }]
Generate random playlistβ
Select random tracks for a shuffled playlist. Ideal for music apps, content recommendations, or quiz questions.
const allSongs = ["Song A", "Song B", "Song C", "Song D", "Song E", "Song F"];
const playlist = sampleSize(allSongs, 4);
// => ["Song C", "Song A", "Song F", "Song D"]
Random survey participantsβ
Select a random subset of users for surveys or feedback. Useful for user research, A/B testing, or focus groups.
const allUsers = [
{ id: "u1", name: "Alice" },
{ id: "u2", name: "Bob" },
{ id: "u3", name: "Charlie" },
{ id: "u4", name: "Diana" },
{ id: "u5", name: "Eve" },
];
const surveyGroup = sampleSize(allUsers, 2);
// => [{ id: "u3", name: "Charlie" }, { id: "u1", name: "Alice" }]
Pick random featured items for a homepage carouselβ
Select a random subset of products or articles for a rotating carousel. Essential for homepages and landing pages with dynamic featured content.
const allFeatured = [
{ id: "p1", title: "Summer Collection", image: "/img/summer.jpg" },
{ id: "p2", title: "New Arrivals", image: "/img/new.jpg" },
{ id: "p3", title: "Best Sellers", image: "/img/best.jpg" },
{ id: "p4", title: "Flash Sale", image: "/img/sale.jpg" },
{ id: "p5", title: "Editor's Pick", image: "/img/pick.jpg" },
];
const carouselSlides = sampleSize(allFeatured, 3);
// => 3 random slides for the homepage carousel
renderCarousel(carouselSlides);