Home > Web Front-end > JS Tutorial > body text

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

Barbara Streisand
Release: 2024-10-29 07:14:02
Original
1082 people have browsed it

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>
Copy after login
  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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template