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

Spread the love

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 the array sort method.

For instance, we write

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

to call array.sort to return a shuffled version of array.

Then we call shuffled.slice with 0 and 5 to return an array with the first 5 elements of the shuffled array.

Conclusion

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

Leave a Reply

Your email address will not be published.