Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *