Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Array(n) and [...Array(n)]

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> ] ]
like image 803
Veeshoo Avatar asked Aug 22 '18 08:08

Veeshoo


People also ask

What is difference between Arr and& Arr?

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.

What is the difference between array and integer?

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.

What is the difference between 10 and 10 1 in Python?

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.


1 Answers

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.

like image 179
Madara's Ghost Avatar answered Sep 20 '22 08:09

Madara's Ghost