get a sample of 5 elements from an array without replacement in javascript

To get a sample of 5 elements from an array without replacement in javascript, you can use the sort() function in combination with the splice() function.

Here's an example code snippet that demonstrates how to do this:

index.tsx
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Shuffle the array
array.sort(() => Math.random() - 0.5);

// Get a sample of 5 elements from the array without replacement
const sample = array.splice(0, 5);

console.log(sample); // [5, 8, 10, 1, 7]
251 chars
10 lines

Here's how this code works:

  • First, we define an array with 10 elements.
  • Next, we use the sort() function to shuffle the array randomly. We do this by passing in a function to sort() that compares two elements and returns a random number that is either negative, zero, or positive. This random comparison function will ensure that the array is shuffled randomly.
  • Finally, we use the splice() function to get a sample of 5 elements from the array without replacement. The splice() function takes two arguments: the starting index of the sample (which is 0), and the number of elements to include in the sample (which is 5). This will give us a new array with 5 elements selected randomly from the original array. And since we used splice(), these 5 elements are removed from the original array, ensuring that we get a sample without replacement.

gistlibby LogSnag