Created
July 4, 2024 04:38
-
-
Save pSapien/a4bc844d3d9bc416f18f67f0c2276aa4 to your computer and use it in GitHub Desktop.
Get random samples from an array by the number of count
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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