Reputation: 185
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> ] ]
Upvotes: 8
Views: 135
Reputation: 174957
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.
Upvotes: 9