How to create a 2d array of zeroes in javascript?
function zero2D(rows, cols) {
var array = [], row = [];
while (cols--) row.push(0);
while (rows--) array.push(row.slice());
return array;
}
Solution 2017:
Late to the Party, but this Post is still high up in the Google search results.
To create an empty 2D-Array with given size (adaptable for more dimensions):
let array = Array(rows).fill().map(() => Array(columns));
Prefilled 2D-Array:
let array = Array(rows).fill().map(() => Array(columns).fill(0));
E.g.:
Array(2).fill().map(() => Array(3).fill(42));
// Result:
// [[42, 42, 42],
// [42, 42, 42]]
Warning:
Array(rows).fill(Array(columns))
will result in all rows being the reference to the same array!!
Update 24th September 2018 (thanks to @Tyler):
Another possible approach is to use Array.fill()
to apply the map function.
E.g.:
Array.from(Array(2), _ => Array(3).fill(43));
// Result:
// [[43, 43, 43],
// [43, 43, 43]]
Benchmark:
https://jsperf.com/multi-dimensional-array-map-vs-fill/5
Well, you could write a helper function:
function zeros(dimensions) {
var array = [];
for (var i = 0; i < dimensions[0]; ++i) {
array.push(dimensions.length == 1 ? 0 : zeros(dimensions.slice(1)));
}
return array;
}
> zeros([5, 3]);
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
Bonus: handles any number of dimensions.