The source array to sample from
The number of elements to sample
An array containing the randomly selected elements
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
RandomGenerator.sample(numbers, 3); // e.g. [2, 7, 9]
RandomGenerator.sample(numbers, 5); // e.g. [1, 4, 6, 8, 10]
RandomGenerator.sample(numbers, 15); // returns all 10 elements (capped at array length)
// Sample users for testing
const allUsers = await getUsersFromDatabase();
const testUsers = RandomGenerator.sample(allUsers, 10);
// Create random product selections
const featuredProducts = RandomGenerator.sample(allProducts, 5);
// Generate test data subsets
const validationSet = RandomGenerator.sample(trainingData, 100);
// Random A/B testing groups
const groupA = RandomGenerator.sample(allParticipants, 50);
const remaining = allParticipants.filter(p => !groupA.includes(p));
const groupB = RandomGenerator.sample(remaining, 50);
Randomly samples a specified number of unique elements from an array.
Selects random elements from the input array without replacement, ensuring all returned elements are unique. The sample size is automatically capped at the array length to prevent errors. Uses a Set-based approach to guarantee uniqueness of selected indices. Ideal for creating test datasets or selecting random subsets for validation.