Languages
[Edit]
EN

JavaScript - get multiple random elements from array

0 points
Created by:
MindOfMadness3
696

In this article, we would like to show you how to get multiple random elements from array in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

const array = ['a', 'b', 'c', 'd'];
const n = 2; // number of elements we want to get
const shuffledArray = array.sort(() => 0.5 - Math.random()); // shuffles array
const result = shuffledArray.slice(0, n); // gets first n elements after shuffle

console.log(result);

Note:

This solution is not optimal for large arrays, since the slice() method creates a copy of the array.

 

Alternative solutions

There are two optimal solutions to this problem, depending on the case we are considering:

  1. getting unique elements from an array (unique indexes) - see the article,
  2. getting unique values from an array - see the article.

References

  1. Math.random() - JavaScript | MDN
  2. Array.prototype.sort() - JavaScript | MDN
  3. Array.prototype.slice() - JavaScript | MDN

Alternative titles

  1. JavaScript - get number of random elements from array
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join