Home > Article > Web Front-end > How to Randomly Select Multiple Elements from an Array in JavaScript?
How to Randomly Select Multiple Elements from an Array
JavaScript offers an array element randomization function using Math.floor(Math.random()*items.length). However, this method only selects a single element. For selecting multiple elements, we need a more comprehensive approach.
Solution:
To obtain multiple random elements from an array, we can implement the following two-step process:
Shuffle the array to randomize the element order:
const shuffled = array.sort(() => 0.5 - Math.random());
Extract a sub-array of the desired length from the shuffled array:
let selected = shuffled.slice(0, n);
Demonstration:
In the example code, we declare an array of numbers array and specify the number of elements to extract (n). By shuffling the array and slicing it, we obtain a sub-array selected containing n random elements.
n = 5; array = Array.from({ length: 50 }, (v, k) => k * 10); // [0,10,20,30,...,490] var shuffled = array.sort(function(){ return 0.5 - Math.random() }); var selected = shuffled.slice(0,n); document.querySelector('#out').textContent = selected.toString();
This approach provides a flexible and efficient way to randomly select multiple elements from an array, regardless of its size.
The above is the detailed content of How to Randomly Select Multiple Elements from an Array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!