To get a sample of 5 elements from an array in Typescript, you can use the following algorithm:
index.ts497 chars21 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