How to Fill an Array with Consecutive Numbers in JavaScript?

Estimated read time 1 min read

To fill an array with consecutive numbers in JavaScript, you can use the Array.from method with a map function:

const size = 10;
const arr = Array.from({length: size}, (_, i) => i + 1);
console.log(arr);

Alternatively, you can use a for loop:

const size = 10;
const arr = [];
for (let i = 1; i <= size; i++) {
  arr.push(i);
}
console.log(arr);

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply