{

How to create array of numbers in javascript


It is a short tutorial on how to create an array with a sequence of numbers.

This tutorial covers multiple ways we can do

how to create an array of numbers for a given range in javascript?

Using for loop with index assigned with initial number and increment by 1 until end of the number, and add an index to an array.

Here is an example to create an array of sequence numbers for 1 to 50.

var numbers = [];
for (var i = 1; i <= 50; i++) {
    numbers.push(i);
}
console.log(numbers)

Output:

[
  1, 2, 3, 4,  5,6, 7, 8, 9, 10
]

using the ES6 spread operator

es6 provides spread operator uses to include an array of values of an array.

Generated sequence of numbers using spread operator and keys method in es6

var array = [...Array(10).keys()];
console.log(array)

output:

[
  0, 1, 2, 3, 4,5, 6, 7, 8, 9
]

Also, you can use Arrays.from() function in place of spread operator

var array = Array.from(Array(10).keys());
console.log(array)

The above two examples generate numbers from zero.

if you want to generate from 1, Here is a code. It uses arrow function with increment values by 1.

var array = Array.from(Array(10).keys(),n=>n+1);
console.log(array)

Output:

[
  1, 2, 3, 4,  5,6, 7, 8, 9, 10
]

lodash range function

if the application uses the lodash library, It provides a range function that iterates with a range of min and max values. Syntax:

_.range([start], stop, [step])

Here is an

start: It is a starting number or initial number, Stop: is the maximum value that needs to increment too. Step: needs value which increments by how much value, Default is 1.

_.range(1, 10);

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Underscore times function

times function uses to iterate the loop a given number of times and each iteration calls the callback function.

_.times(numberoftimes,callbackfunction);

number: It iterates multiple times with the given call-back function. callbackfunction: This function called for each iteration

array = [];
_.times( 5, function( i ){ array.push( i ++ ) } );

Output:

[1, 2, 3, 4, 5]

Conclusion

Learn multiple ways to create an array of sequence numbers for a given min and max values in javascript

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.