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.
Generating a Random Integer Array in a Specific Range
To generate an array of random integers within a specific range, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use
Array.from()to create an empty array of the desired length. - Use
Math.random()to generate random numbers and map them to the specified range. UseMath.floor()to convert them into integers. - The function
randomIntArrayInRange()takes three arguments:min,max, and an optional argumentn(default value is 1). - Call the
randomIntArrayInRange()function with the desiredmin,max, andnvalues 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.