Skip to content

Instantly share code, notes, and snippets.

@NicmeisteR
Created January 18, 2021 10:35
Show Gist options
  • Save NicmeisteR/07b96c7872165a1f7fc72e608832eac2 to your computer and use it in GitHub Desktop.
Save NicmeisteR/07b96c7872165a1f7fc72e608832eac2 to your computer and use it in GitHub Desktop.
Select Specific Amount of Random Items From Object Array.
getRandom(arr, n) {
let result = new Array(n),
len = arr.length,
taken = new Array(len);
if (n > len){
n = arr.length;
result = new Array(n);
}
// throw new RangeError("getRandom: more elements taken than available");
while (n--) {
const x = Math.floor(Math.random() * len);
result[n] = arr[x in taken ? taken[x] : x];
taken[x] = --len in taken ? taken[len] : len;
}
console.log(result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment