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

To get a sample of 5 elements from an array with replacement in javascript, you can use the following code:

index.tsx
function getRandomSampleWithReplacement(array, size) {
  var sample = [];
  
  for (var i = 0; i < size; i++) {
    var randomIndex = Math.floor(Math.random() * array.length);
    sample.push(array[randomIndex]);
  }

  return sample;
}

var myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var mySample = getRandomSampleWithReplacement(myArray, 5);

console.log(mySample);
364 chars
16 lines

In this code, getRandomSampleWithReplacement is a function that takes an array and the desired sample size as arguments, and returns the random sample with replacement. It works by looping size times and selecting a random index from the array using Math.floor(Math.random() * array.length). This index is then used to retrieve the corresponding element from the array, which is added to the sample array. Finally, the function returns the sample.

In the example code, we define an array myArray and call the getRandomSampleWithReplacement function with an argument of 5 to get a sample of 5 elements with replacement. We then log the resulting sample to the console.

gistlibby LogSnag