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> ] ]
arr is an integer pointer (int*) which points the first element of the array. &arr is an integer array pointer (int*)[5] which points the whole array. (all five elements.) &arr is a pointer to an entire array.
int is a number, it's a primitive type. Integer is an object. When you have an array of Integer s, you actually have an array of objects. Array of int s is an array of primitive types.
An array with a size of (10,1) is a 2D array containing empty columns. An array with a size of (10,) is a 1D array.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With