Lodash sampleSize with Full Collection Length

This article examines what happens when you invoke Lodash’s _.sampleSize function with a sample size that exactly matches the length of the target collection. It outlines the function's core mechanics, demonstrates its functional equivalence to other utility methods, and provides code examples illustrating the output and behavior.

When you pass a size argument (n) to _.sampleSize that equals the exact length of the collection, Lodash returns a new array containing every element from the original collection in a randomly shuffled order.

Because _.sampleSize extracts unique elements without replacement, requesting the full count ensures that no elements are dropped or duplicated. Every item from the source collection is guaranteed to be present in the returned array, but their positions will be randomized.

Functionally, calling _.sampleSize(collection, collection.length) yields the exact same result as calling Lodash's _.shuffle(collection) method. Under the hood, Lodash uses an implementation based on the Fisher-Yates shuffle algorithm. When the requested sample size matches the total number of items, the algorithm processes the entire collection, effectively performing a full shuffle.

Here is a basic code example illustrating this behavior:

const _ = require('lodash');

const numbers = [1, 2, 3, 4, 5];
const sampled = _.sampleSize(numbers, numbers.length);

console.log(sampled); 
// Output: A randomized array of all 5 items, e.g., [4, 1, 5, 2, 3]

console.log(sampled.length === numbers.length); 
// Output: true

The original collection remains completely unmodified. Lodash treats input collections immutably in this context, copying elements to a new array rather than altering the source array in place.

If you pass an argument larger than the collection length, Lodash clamps the requested size to the total length of the array, resulting in the same shuffled output as passing the exact length. Therefore, whenever the sample size meets or exceeds the collection length, _.sampleSize simply functions as an alias for a full array shuffle.