sample
Returns a new array with a specified number of unique random elements.
1/**
2 * Returns a new array with a specified number of unique random elements.
3 *
4 * @param arr - The input array to sample from.
5 * @param count - The number of random elements to select.
6 * @returns A new array with randomly selected elements (no duplicates).
7 */
8export function sample<T>(arr: T[], count: number): T[] {
9 const result: T[] = [];
10 const copy = [...arr];
11
12 while (result.length < count && copy.length) {
13 const index = Math.floor(Math.random() * copy.length);
14 result.push(copy.splice(index, 1)[0]);
15 }
16
17 return result;
18}
Ensures unique random values
Elements are removed from a copy of the input array as they are selected, guaranteeing no duplicates in the result.
Preserves original array
The function is non-mutating; it operates on a shallow copy of the input array, maintaining the integrity of the original data.
Safe for short arrays
Automatically limits sampling to the maximum number of available elements, preventing out-of-bounds errors if
count > arr.length
.Simple and efficient
Uses in-place array mutation (
splice
) and direct indexing to efficiently draw unique samples without extra bookkeeping.
Tests | Examples
1test('sample returns correct count', () => {
2 const result = sample([1, 2, 3, 4, 5], 3);
3 expect(result.length).toBe(3);
4});
5
6test('sample returns unique values', () => {
7 const input = [1, 2, 3, 4, 5];
8 const result = sample(input, 5);
9 const unique = new Set(result);
10 expect(unique.size).toBe(result.length);
11});
12
13test('sample never returns elements outside input', () => {
14 const input = ['a', 'b', 'c'];
15 const result = sample(input, 2);
16 result.forEach((val) => expect(input).toContain(val));
17});
18
19test('sample handles count larger than input gracefully', () => {
20 const input = [1, 2];
21 const result = sample(input, 5);
22 expect(result.length).toBe(2);
23 expect(result).toEqual(expect.arrayContaining(input));
24});
Common Use Cases
Randomized UI content
Useful for displaying a random subset of items (e.g. featured posts, testimonials, products) on a landing page.
Game mechanics / quizzes
Ideal for selecting random questions, options, or levels from a pool without repetition.
Sampling datasets
Used in analytics, A/B testing, or mock data generation where a small randomized slice of a dataset is needed.
Shuffling previews or recommendations
Handy when showing a fresh selection of items each page load or user session.
Avoiding bias in examples or demos
Helps rotate demo content or randomized test cases to avoid hardcoding the same values.