get a sample of 5 elements from an array in typescript

To get a sample of 5 elements from an array in Typescript, you can use the following algorithm:

index.ts
function sample(array: any[], size: number): any[] {
  let shuffled = array.slice(0),
      i = array.length,
      min = i - size,
      temp,
      index;

  while (i-- > min) {
    index = Math.floor((i + 1) * Math.random());
    temp = shuffled[index];
    shuffled[index] = shuffled[i];
    shuffled[i] = temp;
  }

  return shuffled.slice(min);
}

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const sampleArray = sample(array, 5);
console.log(sampleArray); // [3, 9, 6, 10, 1] for example
497 chars
21 lines

First, we create a function named sample, which takes an array and the desired size of the sample as arguments. Then, we create a shuffled copy of the input array, which we will randomly remove elements from until we have the desired sample size.

We loop over the shuffled array and swap the current element with another element at a random index within the remaining elements. This ensures that we have a uniform probability of selecting any element in the array.

Finally, we slice the shuffled array to include only the last size elements, which now represent our random sample. The function returns this sliced array, which we can then use however we like.

gistlibby LogSnag