Create Array and fill with index plus one in JavaScript

Viewed 3803

I am trying to create an Array using new Array() and filling with index + 1 but somehow, though array is creating successfully but values are not filling correctly.

Code -

var aa = (new Array(4)).map((x, index) => {
    return index + 1;
});

console.log(aa);

Output - [undefined, undefined, undefined, undefined]

Expected - [1, 2, 3, 4]

Let me know what I am doing wrong here.

2 Answers

map only visits entries that actually exist, it skips gaps in sparse arrays.

There are various ways to do this:

  1. You can use Array.from and its mapping callback:

    const as = Array.from(Array(4), (_, index) => index + 1);
    
    console.log(as);

  2. You can use a simple for loop:

    const as = [];
    for (let index = 1; index <= 4; ++index) {
        as.push(index);
    }
    
    console.log(as);

  3. You can use fill and then map:

    const as = Array(4).fill().map((_, index) => index + 1);
    
    console.log(as);

  4. A variant of fill+map, you can use spread as Igor shows.

[...Array(4)].map((v, i) => i + 1)
Related