4

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.

Nesh
  • 2,164
  • 6
  • 26
  • 47

2 Answers2

8

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.

T.J. Crowder
  • 959,406
  • 173
  • 1,780
  • 1,769
4
[...Array(4)].map((v, i) => i + 1)
Igor Bukin
  • 926
  • 6
  • 13