Home  >  Article  >  Web Front-end  >  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
Patricia ArquetteOriginal
2024-10-29 11:13:29735browse

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>

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!

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