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

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

DDD
Release: 2024-10-30 05:53:02
Original
369 people have browsed it

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

How to Randomly Select Multiple Elements from an Array

JavaScript offers an array element randomization function using Math.floor(Math.random()*items.length). However, this method only selects a single element. For selecting multiple elements, we need a more comprehensive approach.

Solution:

To obtain multiple random elements from an array, we can implement the following two-step process:

  1. Shuffle the array to randomize the element order:

    const shuffled = array.sort(() => 0.5 - Math.random());
    Copy after login
  2. Extract a sub-array of the desired length from the shuffled array:

    let selected = shuffled.slice(0, n);
    Copy after login

Demonstration:

In the example code, we declare an array of numbers array and specify the number of elements to extract (n). By shuffling the array and slicing it, we obtain a sub-array selected containing n random elements.

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();
Copy after login

This approach provides a flexible and efficient way to randomly select multiple elements from an array, regardless of its size.

The above is the detailed content of How to Randomly Select Multiple 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template