Accessing Multiple Random Elements from an Array in JavaScript
When working with arrays, there are scenarios where selecting multiple random elements is necessary. The provided code snippet provides a concise solution to this problem:
<code class="js">// Shuffle array const shuffled = array.sort(() => 0.5 - Math.random()); // Get sub-array of first n elements after shuffled let selected = shuffled.slice(0, n);</code>
Detailed Explanation:
Example:
<code class="js">n = 5; array = Array.from({ length: 50 }, (v, k) => k * 10); var shuffled = array.sort(function () { return 0.5 - Math.random(); }); var selected = shuffled.slice(0, n); console.log(selected); // Output: [490, 470, 480, 460, 450]</code>
This code snippet shuffles an array of 50 elements (multiples of 10) and selects the first 5 elements randomly. The output will be an array containing 5 random elements.
Advantages of this Solution:
The above is the detailed content of How to Select Multiple Random Elements from a JavaScript Array?. For more information, please follow other related articles on the PHP Chinese website!