Home >Web Front-end >JS Tutorial >How to Select Multiple Random Elements from an Array in JavaScript?

How to Select Multiple Random Elements from an Array in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-10-29 07:14:021138browse

How to Select Multiple Random Elements from an Array in JavaScript?

Selecting Multiple Random Elements from an Array

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:

  1. Shuffle the Array: Use the following code to shuffle the array's elements randomly:
<code class="javascript">const shuffled = array.sort(() => 0.5 - Math.random());</code>
  1. Select Desired Elements: Create a sub-array consisting of the first n elements from the shuffled array, where n is the desired number of random elements:
<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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn