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

How to Select Multiple Random Elements from a JavaScript Array?

Linda Hamilton
Release: 2024-11-01 16:48:30
Original
842 people have browsed it

How to Select Multiple Random Elements from a JavaScript Array?

Accessing Multiple Random Elements from an Array in JavaScript

When working with arrays, there are scenarios where selecting multiple random elements is necessary. The provided code snippet provides a concise solution to this problem:

<code class="js">// Shuffle array
const shuffled = array.sort(() => 0.5 - Math.random());

// Get sub-array of first n elements after shuffled
let selected = shuffled.slice(0, n);</code>
Copy after login

Detailed Explanation:

  1. Shuffling the Array: The sort function is used with a custom compare function that essentially shuffles the elements randomly.
  2. Slicing the Shuffled Array: The slice method is then used to extract a sub-array consisting of the first n elements from the shuffled array. This sub-array represents the randomly selected elements.

Example:

<code class="js">n = 5;
array = Array.from({ length: 50 }, (v, k) => k * 10);

var shuffled = array.sort(function () {
  return 0.5 - Math.random();
});
var selected = shuffled.slice(0, n);

console.log(selected); // Output: [490, 470, 480, 460, 450]</code>
Copy after login

This code snippet shuffles an array of 50 elements (multiples of 10) and selects the first 5 elements randomly. The output will be an array containing 5 random elements.

Advantages of this Solution:

  • Efficient and simple to implement.
  • Returns an array of randomly selected elements, preserving the original order of the elements.
  • Can be easily modified to select a different number of random elements.

The above is the detailed content of How to Select Multiple Random Elements from a JavaScript Array?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!