To get a number of random elements from an array with JavaScript, we use the array sort
and Math.random
methods.
For instance, we write
const shuffled = array.sort(() => 0.5 - Math.random());
const selected = shuffled.slice(0, n);
to call sort
to returned a shuffled version of the array
by calling it with a function that returns a random number.
Then we get an array with the first n
items in the shuffled
array with slice
.