Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.map doesn't seem to work on uninitialized arrays [duplicate]

I'm trying to set default values on an uninitialized array using the map function but it doesn't seem to work, any ideas on how to set default values?

Consider this code snippet I tried in Chrome console.

> var N = 10;
> var x = new Array(N);
> x
  [undefined x 10]

> x.map(function(i) { return 0;});
  [undefined x 10]

I was expecting the array to be initialized to 0's.

like image 815
Raja Avatar asked Dec 02 '13 16:12

Raja


2 Answers

If you'd like to fill an array, you can use Array(5).fill() and the methods will then work as expected--see the alternate related answer from aasha7. Older pre-fill approaches include:

Array.apply(null, new Array(5)).map(function() { return 0; });
// [ 0, 0, 0, 0, 0 ]

After some reading one of the posts linked in the comments, I found this can also be written as

Array.apply(null, {length: 5}).map(function() { return 0; });

However, trying to use .map on undefined values will not work.

x = new Array(10);
x.map(function() { console.log("hello"); });

// so sad, no "hello"
// [ , , , , , , , , ,  ]

.map will skip over undefined values :(

like image 104
maček Avatar answered Oct 23 '22 16:10

maček


I'd just like to point out that you can now do:

Array(2).fill().map(_ => 4);

This will return [4, 4].

like image 12
aashah7 Avatar answered Oct 23 '22 17:10

aashah7