Is there an easy way to programmatically create a 2d array in javascript?
What I don't want:
var array2D = [
[0,0,0],
[0,0,0],
[0,0,0]
]
Is there an easy way to programmatically create a 2d array in javascript?
What I don't want:
var array2D = [
[0,0,0],
[0,0,0],
[0,0,0]
]
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.
function zero2D(rows, cols) {
var array = [], row = [];
while (cols--) row.push(0);
while (rows--) array.push(row.slice());
return array;
}