How to Extract Multiple Random Elements from an Array in JavaScript
Problem:
Retrieving a single random element from an array is straightforward using the formula Math.floor(Math.random() * array.length). However, retrieving multiple random elements without duplicates can be challenging.
Solution:
To obtain a specified number of random elements from an array, follow these steps:
Example:
Consider the following code:
<code class="javascript">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();</code>
This code shuffles an array of 50 numbers and retrieves the first 5 random elements, displaying them in the HTML document.
The above is the detailed content of How to Extract Multiple Random Elements from an Array in JavaScript Without Duplicates?. For more information, please follow other related articles on the PHP Chinese website!