Categories
JavaScript Answers

How to Get a Number of Random Elements from a JavaScript Array?

Spread the love

To get a number of random elements from a JavaScript array, we can shuffle it then call slice to get the first n elements from the shuffled array.

For instance, we can write:

const n = 5;
const items = [10, 6, 19, 16, 14, 15, 2, 9, 5, 3, 4, 13, 8, 7, 1, 12, 18, 11, 20, 17];
const sample = items
  .sort(() => Math.random() - 0.5)
  .slice(0, n);
console.log(sample)

We call sort on items with a callback that returns a number between -0.5 and 0.5 to return an array with the items shuffled around.

Then we call slice with 0 and n to get the first n items in the shuffled array.

Then sample has the first 5 shuffled items from items since we set n to 5.

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 *