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

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

index.ts
function getSampleWithReplacement<T>(arr: T[], size: number): T[] {
  const result: T[] = [];
  for (let i = 0; i < size; i++) {
    const randomIndex: number = Math.floor(Math.random() * arr.length);
    result.push(arr[randomIndex]);
  }
  return result;
}

const myArray: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const sample: number[] = getSampleWithReplacement(myArray, 5);
console.log(sample); // output: [1, 8, 6, 4, 2] (randomly selected)
450 chars
13 lines

The getSampleWithReplacement function takes two parameters: the arr array to sample from and the size of the sample. It then generates size number of random indices between 0 and arr.length - 1, and pushes the corresponding elements of the array into a result array. Finally, it returns the resulting sample array.

This implementation uses TypeScript generics to enable sampling of arrays of any type (T).

gistlibby LogSnag