Fill array with incrementing numbers/ intergers using JavaScript
Find out how to fill an array with incrementing numbers/integers using JavaScript's for loop and Array.from() method with keys().
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
Find the average of n numbers using JavaScript
Tutorial to write a JavaScript function to find the average of n numbers of items in an Array using JavaScript.
Best way - Split an array into half in Javascript
To divide an single array into half i.e into two different arrays without modifying the original array we can use Array.slice() method in JavaScript.
Merge Two Arrays and Remove Duplicates - JavaScript
Tutorial on how to merge two or more array and remove duplicates in JavaScript.
How to multiply all numbers in an array using JavaScript
Quick tutorial on how to multiply all the elements in an array using iterative i.e loop and reduce method in JavaScript.
