8

Why there is a difference in map() output in the below code?

var y = [1,2,2,1];

var t = y.map(ind => [...Array(ind)].map((_,i) => ind+""+i));
// This makes [ [ '10' ], [ '20', '21' ], [ '20', '21' ], [ '10' ] ]

var t1 = y.map(ind => Array(ind).map((_,i) => ind+""+i));
//[ [ <1 empty item> ], [ <2 empty items> ], [ <2 empty items> ], [ <1 empty item> ] ]
5
  • please add the wanted result as well. Commented Aug 22, 2018 at 8:58
  • 3
    .map does not loop over scattered indices Commented Aug 22, 2018 at 9:00
  • @Rajesh that's probably the answer OP is looking for. You should make this an answer, with links and everything Commented Aug 22, 2018 at 9:02
  • @Peping Thanks! I have seen a post on this. Was looking for it only Commented Aug 22, 2018 at 9:02
  • As an alternative, you can use Array.from({length: n}, (_, i) => ...) Commented Aug 22, 2018 at 9:08

1 Answer 1

9

This is basically the reason you should avoid using the Array constructor to create arrays.

When passed a single number n as an argument, the Array constructor will return an array with length n, but no elements, also known as a sparse array. (Anything else passed to the Array constructor, a string, an object, two numbers, etc, will create a normal array with the passed arguments as elements in order).

Trying to .map() over this array will not work, since there are no items in it, which is why you get the same sparse arrays. Your .map() is a no-op.

Using [... (Same with Array.from(), by the way) on it, will "realize" the array turning [ <1 empty item> ] into [undefined] and [ <2 empty items> ] into [undefined, undefined], an array with actual elements, whose values are undefined. .map() does work on this, so you get the result you expect.

In short, avoid the Array constructor.

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

2 Comments

The array constructor is a remnant from Ye Olde days of medieval JavaScript. The reasoning behind sparse arrays is foggy.
@Veeshoo To mark a question as "resolved", click on the green tick below the answer's score (that will mark that answer as "accepted"). I noticed you haven't done this for previous questions you've made, it would be nice if you could return to those questions and accept the answers that helped solve your problem (It makes things more organized for the site, rewards the answerer, and gives you a little bonus reputation as well!). You're welcome, hope you enjoy the site! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.