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]
]
Late to the Party, but this Post is still high up in the Google search results.
let array = Array(rows).fill().map(() => Array(columns));
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]]
Array(rows).fill(Array(columns))
will result in all rows being the reference to the same array!!
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]]
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.
function zero2D(rows, cols) {
var array = [], row = [];
while (cols--) row.push(0);
while (rows--) array.push(row.slice());
return array;
}
You can use the following function to create a 2D array of zeros:
const zeros = (m, n) => [...Array(m)].map(e => Array(n).fill(0));
console.log(zeros(3, 4));
// [ [ 0, 0, 0, 0 ],
// [ 0, 0, 0, 0 ],
// [ 0, 0, 0, 0 ] ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With