Random Integer Array in Range

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore how to generate a random integer array within a specified range using JavaScript. We will use the Array.from() method to create an empty array and fill it with randomly generated integers using Math.random() and Math.floor(). By the end of this lab, you will have a solid understanding of how to generate random integers in JavaScript and apply this knowledge to your own projects.


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/AdvancedConceptsGroup -.-> javascript/destr_assign("`Destructuring Assignment`") subgraph Lab Skills javascript/variables -.-> lab-28572{{"`Random Integer Array in Range`"}} javascript/data_types -.-> lab-28572{{"`Random Integer Array in Range`"}} javascript/arith_ops -.-> lab-28572{{"`Random Integer Array in Range`"}} javascript/comp_ops -.-> lab-28572{{"`Random Integer Array in Range`"}} javascript/destr_assign -.-> lab-28572{{"`Random Integer Array in Range`"}} end

Generating a Random Integer Array in a Specific Range

To generate an array of random integers within a specific range, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use Array.from() to create an empty array of the desired length.
  3. Use Math.random() to generate random numbers and map them to the specified range. Use Math.floor() to convert them into integers.
  4. The function randomIntArrayInRange() takes three arguments: min, max, and an optional argument n (default value is 1).
  5. Call the randomIntArrayInRange() function with the desired min, max, and n values to generate the random integer array.

Here's the code:

const randomIntArrayInRange = (min, max, n = 1) =>
  Array.from(
    { length: n },
    () => Math.floor(Math.random() * (max - min + 1)) + min
  );

Example usage:

randomIntArrayInRange(12, 35, 10); // [ 34, 14, 27, 17, 30, 27, 20, 26, 21, 14 ]

Summary

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

Other JavaScript Tutorials you may like