Skip to content

Instantly share code, notes, and snippets.

@GGrassiant
Last active December 30, 2021 20:44
Show Gist options
  • Save GGrassiant/b0026df5ac688361ef2f9b4934e9cbd6 to your computer and use it in GitHub Desktop.
Save GGrassiant/b0026df5ac688361ef2f9b4934e9cbd6 to your computer and use it in GitHub Desktop.
Random values from Array (from Stack Overflow)

Random values from array

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