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