5

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.

1
  • 1
    Thank you @adiga. I knew it would be there, just couldn't find it. Commented Jul 6, 2020 at 13:58

2 Answers 2

15

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Answer reflex. Sigh. I'm sure there's a dup;etarget. Marked CW and off to find it...
Why map over something you don't have to Array(size + 1).fill().unshift() or whatever other method you may prefer splice, slice, etc.
@MarceDev - That fills the array with undefined. The OP wants to fill it with the index + 1.
5
[...Array(4)].map((v, i) => i + 1)

1 Comment

maybe a bit simpler: new Array(4).fill(null).map((v, i) => i++)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.