Random values from array
Last active
December 30, 2021 20:44
-
-
Save GGrassiant/b0026df5ac688361ef2f9b4934e9cbd6 to your computer and use it in GitHub Desktop.
Random values from Array (from Stack Overflow)
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 getRandom(arr, n) { | |
const result = new Array(n); | |
let len = arr.length; | |
const taken = new Array(len); | |
if (n > len) | |
throw new RangeError("getRandom: more elements taken than available"); | |
while (n--) { | |
const x = Math.floor(Math.random() * len); | |
result[n] = arr[x]; | |
taken[x] = --len in taken ? taken[len] : len; | |
} | |
return result; | |
} | |
const array = [1, 2, 3, 4, 5, 6, 7, 8]; | |
const number = 2; | |
console.log(getRandom(array, number)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment