Get Multiple Random Elements from an Array in JavaScript

avatar

Borislav Hadzhiev

Thu Oct 28 20212 min read

Get Multiple Random Elements from an Array #

To get multiple random elements from an array, use the sort() method on the array to shuffle the array elements in a random order, e.g. arr.sort(() => 0.5 - Math.random()). Then call the slice() method on the shuffled array to get multiple random elements.

index.js
function getMultipleRandom(arr, num) { const shuffled = [...arr].sort(() => 0.5 - Math.random()); return shuffled.slice(0, num); } const arr = ['b', 'c', 'a', 'd']; console.log(getMultipleRandom(arr, 2)); // πŸ‘‰οΈ ['a', 'c']; console.log(getMultipleRandom(arr, 3)); // πŸ‘‰οΈ ['c', 'b', 'c']

We created a reusable function that takes an array and the number of random elements we want to get back.

The first step is to use the spread syntax (...) to create a shallow copy of the original array.

We do this, because the Array.sort method sorts the values of the array, changing its contents.

The spread syntax (...) helps us to avoid mutating the passed in array.

The only parameter we passed to the sort() method is a compare function.

This function gets called with a pair of array elements (a and b) and defines the sort order of the array.

We used the Math.random function, because we want a randomly sorted array.

The Math.random function returns a random number from 0 up to 1 (but not including 1).

index.js
console.log(Math.random()) // πŸ‘‰οΈ 0.99453534... console.log(Math.random()) // πŸ‘‰οΈ 0384848858... console.log(Math.random()) // πŸ‘‰οΈ 0.58584833... console.log(0.5 - Math.random()); // πŸ‘‰οΈ -0.10394939... console.log(0.5 - Math.random()); // πŸ‘‰οΈ 0.364345434... console.log(0.5 - Math.random()); // πŸ‘‰οΈ 0.075445654...

The compare function we passed to the sort() method gets called with 2 array elements every time - a and b. These are the 3 scenarios that could happen on each iteration:

  • If the return value from the compare function is greater than 0, then element b gets sorted before a.
  • If the return value is less than 0, then element a gets sorted before b.
  • If the return value is equal to 0, then the original order of the array elements is kept.
Because the Math.random function returns a float from 0 to 1, we picked a number in the middle (0.5) from which we subtract the result from Math.random.

This gets us an array containing the same values in a different order.

The last step is to use the Array.slice method to get multiple elements from the shuffled array.

The parameters we passed to the slice method are:

  1. start index - the index of the first element to be included in the new array.
  2. end index - extract elements up to, but not including this index.
The slice method returns a new array containing multiple elements from the shuffled array.

Here are the steps we took to get multiple random elements from an array:

  1. Sort the array in a random order.
  2. Get a slice from the shuffled array containing as many elements as we need.

Here's the complete example.

index.js
function getMultipleRandom(arr, num) { const shuffled = [...arr].sort(() => 0.5 - Math.random()); return shuffled.slice(0, num); } const arr = ['b', 'c', 'a', 'd']; console.log(getMultipleRandom(arr, 2)); // πŸ‘‰οΈ ['d', 'a']; console.log(getMultipleRandom(arr, 3)); // πŸ‘‰οΈ ['b', 'a', 'c']

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee