EN
JavaScript - get multiple random elements from array
0
points
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:
- getting unique elements from an array (unique indexes) - see the article,
- getting unique values from an array - see the article.