is there a shorter, better way to generate \'n\' length 2D array?
var a = (function(){ var i=9, arr=[]; while(i--) arr.push([]); return arr })();
a // [ [],
Just discovered another ES6 way with one line expression:
Array.from({length: N}, () => [])
Array.from(arrayLike[, mapFn[, thisArg]])
More detail about its implementation/polyfill ⇢ MDN Array.from()
Yet another neat solution with help of array spread syntax
:
[...Array(N)].map(() => [])
for(var i=9,a=[];i>=0;i--){ a.push([]) }
shorter way can be :
for(var i=9,a=[];i>=0;i--){ a.push([]) }
Array(cardinality).fill(0).map(function(item) {return [];});
where cardinality is the number of items you are looking at. In this case it would be 9. This was suggested by one of my colleagues actually. This is neat, I think :) This is valid from ECMA V6. Documentation: Array::fill
var a = []; for(var i=0;i<10;i++) { a[i] = []; }
var a = [];
var max_length = 10;
for(var i = 0; i < max_length; ++i){
a[i] = [];
}