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> ] ]
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
Veeshoo
  • 185
  • 4

1 Answers1

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.

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
  • The array constructor is a remnant from Ye Olde days of medieval JavaScript. The reasoning behind sparse arrays is foggy. – Madara's Ghost Aug 22 '18 at 09:10
  • @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! :) – Madara's Ghost Aug 22 '18 at 12:57