Fill array with incrementing numbers/ intergers using JavaScript

featured Image

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 ]

Related Posts

featured Image

Get the 10 characters from a string using JavaScript.

Here, in this article we will learn how to get the first 10 character from any string using JavaScript. Here we will be using JavaScript’s String method substring. What is…

Read more
featured Image

Convert date to long date format using JavaScript

In this article we will look into how to convert a date to a long date format using JavaScript. To convert it to a long format we will be using…

Read more
featured Image

Prevent body from scrolling when a modal is opened

Here, in this article, we will learn how to prevent the body from scrolling when a modal or a pop-up is opened using JavaScript. The scroll event is not cancelable….

Read more