Skip to content
Home » Program to Generate an Array with a Specified Range

Program to Generate an Array with a Specified Range

This blog post will discuss how to write a program using JavaScript that generates an array with a specified range of numbers.

Code

[...Array(N)].map((_, i) => from + i * step);

Code Explanation

The provided code snippet is a concise way to generate an array with a specified range of numbers. Let’s break it down:

javascript
[...Array(N)].map((_, i) => from + i * step);

Here’s how it works:

1. The Array(N) creates an array with a length of N, with each element initialized as undefined.

2. The spread operator ... deconstructs the array, so that each element is spread out as individual arguments.

3. The map() function is then called on the deconstructed array, which allows us to perform a specific operation on each element and return a new array with the results.

4. The map() function takes two arguments:

– The first argument (_, i) represents the current element and its index, respectively. We use _ as a placeholder for the current element, as we are only interested in the index in this case.

– The arrow function => signifies the start of the function’s body.

5. Inside the arrow function, we calculate the value for each element in the new array using the formula from + i * step. Here, from represents the starting value of the range, i represents the index of the current element, and step represents the increment between each element.

6. Finally, the resulting array with the specified range of numbers is returned.

To use this code snippet, you need to replace N, from, and step with the desired values. For example, if you want to generate an array with a range of numbers from 1 to 10 with a step of 2, you would replace N with 10, from with 1, and step with 2.

Example usage:

javascript
const rangeArray = [...Array(10)].map((_, i) => 1 + i * 2);
console.log(rangeArray); // Output: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

In this example, the code generates an array with a range of numbers from 1 to 10, incrementing by 2. The resulting array is then logged to the console.

In conclusion, the provided code snippet offers a concise and efficient way to generate an array with a specified range of numbers in JavaScript. It can be easily customized by replacing the values for N, from, and step based on your requirements. Happy coding!

Also checkout the following codes.


How to Generate an Array with Incrementing Values using JavaScript?
Program to Generate a Range of Numbers in JavaScript