Skip to main content

sampleSize()

sampleSize<T>(array, n): T[]

Gets n random elements from an array.

note

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" }]

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);