Skip to content

Instantly share code, notes, and snippets.

@pSapien
Created July 4, 2024 04:38
Show Gist options
  • Save pSapien/a4bc844d3d9bc416f18f67f0c2276aa4 to your computer and use it in GitHub Desktop.
Save pSapien/a4bc844d3d9bc416f18f67f0c2276aa4 to your computer and use it in GitHub Desktop.
Get random samples from an array by the number of count
function getRandomSamplesByCount<T>(arr: T[], count: number) {
const randomSamples = [];
const inputCopy = arr.slice();
for (let i = 0; i < count; i++) {
if (inputCopy.length === 0) break;
const randomIndex = Math.floor(Math.random() * inputCopy.length);
const [randomSample] = inputCopy.splice(randomIndex, 1)
randomSamples.push(randomSample);
}
return randomSamples;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment