best way to generate empty 2D array
Solution 1:
Another way:
for(var a = [];a.length < 10; a.push([])); // semicolon is mandatory here
Yet another way:
var a = []; while(a.push([]) < 10);
This works because .push()
[docs] (specification) returns the new length of the array.
That said, this is the wrong way of "reducing code". Create a dedicated function with a meaningful name and use this one. Your code will be much more understandable:
function get2DArray(size) {
size = size > 0 ? size : 0;
var arr = [];
while(size--) {
arr.push([]);
}
return arr;
}
var a = get2DArray(9);
Code is read much more often than written.
Solution 2:
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(() => [])
Solution 3:
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