N Random Elements in Array

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to select random elements from an array using JavaScript. We will learn how to shuffle an array using the Fisher-Yates algorithm and use it to randomly select one or more elements from an array. This lab is designed to enhance your understanding of array manipulation and improve your problem-solving skills in JavaScript.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/loops("`Loops`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28503{{"`N Random Elements in Array`"}} javascript/data_types -.-> lab-28503{{"`N Random Elements in Array`"}} javascript/arith_ops -.-> lab-28503{{"`N Random Elements in Array`"}} javascript/comp_ops -.-> lab-28503{{"`N Random Elements in Array`"}} javascript/loops -.-> lab-28503{{"`N Random Elements in Array`"}} javascript/array_methods -.-> lab-28503{{"`N Random Elements in Array`"}} javascript/spread_rest -.-> lab-28503{{"`N Random Elements in Array`"}} end

Code Practice: Getting Random Elements from an Array

To practice coding, open the Terminal/SSH and type node. The following code utilizes the Fisher-Yates algorithm to shuffle an array and retrieve n random, unique elements at unique keys from the array, up to the size of the array.

const sampleSize = ([...arr], n = 1) => {
  let m = arr.length;
  while (m) {
    const i = Math.floor(Math.random() * m--);
    [arr[m], arr[i]] = [arr[i], arr[m]];
  }
  return arr.slice(0, n);
};

To use this code, call sampleSize() with an array and an optional number n of elements to retrieve. If n is not provided, the function will return only one element at random from the array.

sampleSize([1, 2, 3], 2); // [3, 1]
sampleSize([1, 2, 3], 4); // [2, 3, 1]

Summary

Congratulations! You have completed the N Random Elements in Array lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like