Fill array with incrementing numbers/ intergers using JavaScript

In this article, we will see different ways to fill an array with incrementing numbers/integers using JavaScript.

To fill an array with every number in a sequence we can use two methods:

  • Using for loop, and
  • Using Array.from() method

Let’s see each method with examples

Using for loop to fill an array in JavaScript.

We can use for loop to push numbers in an incrementing sequence.

var myArr = []
for(let i=0; i < 5; i++){
  myArr.push(i)
}

console.log(myArr) // [ 0, 1, 2, 3, 4 ]

Here, we have used a for loop to iterate numbers in incrementing form till i<5, and on each loop it pushes the number to the myArr empty array.

We can create a function to give the N number as user input.

function incrementArr(num){
  var myArr = []
  for(let i=0; i < num; i++){
  myArr.push(i)
  }
    return myArr;
}

console.log(incrementArr(10)) // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

Here, we can pass a number as an argument, till which you want the number/integer to increment.

Using Array.from method to fill an array

In ES6, we can use the Array.from() method along with the Array() and keys() method to fill an array with a sequence of incrementing numbers.

The keys() method in JavaScript returns a new Array Iterator object that contains keys for each index in the array.

The Array.from() method creates a shallow-copied Array instance from an array or any iterable object in Javascript.

Array.from(Array(10).keys())

The Array() create a new Array object.

We can write a shorter version using the spread operator like this,

[...Array(10).keys()]

Output:

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

As you can see the array starts with 0 (the first index) but if we want to start it from 1, we need to do some adjustments using map(), like this

[...Array(10).keys()].map(i => i+1)

Now the output will be

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