I am trying to generate a 2D n*m array in javascript full of zeros. What is the fastest way of doing that?
I know the simple for loop would be enough to set all the elements to 0, but what I would like to know, why can’t I do that with mapping. For example with the underscore lib (or even the native map)
_.map(Array(n),function(a){return 0}) // makes {undefined,undefined,...}
while
_.map([1,2,3,5,6],function(a){return 0}) // makes {0,0,0,0,0}
Can anyone explain if I can fill an empty array with a map function and how, or why not?
PS: There is a trivial solution to my problem, I am just asking this cause I would like to learn more, and I cant find a good enough answer on google. Thank you
Typical JavaScript
.map()functions ignore array members that areundefined. That’s whyArray(n)doesn’t work.You could easily add a method to
Array.prototypeto do a quick fill…then…