Created
January 18, 2021 10:35
-
-
Save NicmeisteR/07b96c7872165a1f7fc72e608832eac2 to your computer and use it in GitHub Desktop.
Select Specific Amount of Random Items From Object Array.
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
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