In JavaScript, you may often want to randomly retrieve one or more elements from an array. While the standard approach, such as the one mentioned in the given link, enables accessing a single item, what if you require multiple random elements?
To achieve this, utilize a two-step process:
<code class="javascript">const shuffled = array.sort(() => 0.5 - Math.random());</code>
<code class="javascript">let selected = shuffled.slice(0, n);</code>
Demo:
<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>
In this demonstration, the selected array will now contain n random elements from the original array.
The above is the detailed content of How to Select Multiple Random Elements from an Array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!