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

How to Extract Multiple Random Elements from an Array in JavaScript Without Duplicates?

Patricia Arquette
Release: 2024-10-29 11:13:29
Original
829 people have browsed it

How to Extract Multiple Random Elements from an Array in JavaScript Without Duplicates?

How to Extract Multiple Random Elements from an Array in JavaScript

Problem:

Retrieving a single random element from an array is straightforward using the formula Math.floor(Math.random() * array.length). However, retrieving multiple random elements without duplicates can be challenging.

Solution:

To obtain a specified number of random elements from an array, follow these steps:

  1. Shuffle the array using array.sort(() => 0.5 - Math.random()). This line ensures that the elements in the array are randomized.
  2. Extract the first n elements from the shuffled array using selected = shuffled.slice(0, n). This line selects the first n elements from the shuffled array.

Example:

Consider the following code:

<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

This code shuffles an array of 50 numbers and retrieves the first 5 random elements, displaying them in the HTML document.

The above is the detailed content of How to Extract Multiple Random Elements from an Array in JavaScript Without Duplicates?. 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