How to get a number of random elements from an array with JavaScript?

Sometimes, we want to get a number of random elements from an array with JavaScript.

In this article, we’ll look at how to get a number of random elements from an array with JavaScript.

How to get a number of random elements from an array with JavaScript?

To get a number of random elements from an array with JavaScript, we call array sort to shuffle the array.

Then we get a subarray from the shuffled array with slice.

For instance, we write

const shuffled = array.sort(() => 0.5 - Math.random());
const selected = shuffled.slice(0, n);

to call array.sort with a callback that returns a number between -0.5 and 0.5 to return a shuffled version of array.

And then we call shuffled.slice with 0 and n to get the first n elements.

Conclusion

To get a number of random elements from an array with JavaScript, we call array sort to shuffle the array.

Then we get a subarray from the shuffled array with slice.