javascript select n random elements from an array code example
Example 1: javascript get n random elements from array
const shuffled = array.sort(() => 0.5 - Math.random());
let selected = shuffled.slice(0, n);
Example 2: get n random items from array javascript
function getRandom(arr, n) {
var result = new Array(n),
len = arr.length,
taken = new Array(len);
if (n > len)
throw new RangeError("getRandom: more elements taken than available");
while (n--) {
var x = Math.floor(Math.random() * len);
result[n] = arr[x in taken ? taken[x] : x];
taken[x] = --len in taken ? taken[len] : len;
}
return result;
}