# JavaScript: Generate an array of specified length, the content of the array is integer numbers, increase by one from starting

## JavaScript Array: Exercise-40 with Solution

Write a JavaScript function to generate an array of integer numbers, increasing one from the starting position, of a specified length.

Test Data :
console.log(array_range(1, 4));
[1, 2, 3, 4]
console.log(array_range(-6, 4));
[-6, -5, -4, -3]

Visual Presentation:

Sample Solution:

JavaScript Code:

``````// Function to generate an array of numbers in a specified range
function array_range(start, len)
{
// Create a new array with the specified length
var arr = new Array(len);

// Iterate through the array, filling it with values incremented from 'start'
for (var i = 0; i < len; i++, start++)
{
arr[i] = start;
}

// Return the generated array
return arr;
}

// Output the result of generating an array with a starting value of 1 and a length of 4
console.log(array_range(1, 4));

// Output the result of generating an array with a starting value of -6 and a length of 4
console.log(array_range(-6, 4));
``````

Output:

```[1,2,3,4]
[-6,-5,-4,-3]
```

Flowchart:

ES6 Version:

``````// Function to generate an array of numbers in a specified range
function array_range(start, len)
{
// Create a new array with the specified length using Array.from
const arr = Array.from({ length: len }, (_, index) => start + index);

// Return the generated array
return arr;
}

// Output the result of generating an array with a starting value of 1 and a length of 4
console.log(array_range(1, 4));

// Output the result of generating an array with a starting value of -6 and a length of 4
console.log(array_range(-6, 4));
``````

Live Demo:

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿