Since the answer is in the comments, I'm posting this as an official answer for anyone visiting later:
There are a couple of ways to create a 2D array in Javascript.
- Simple, straight-forward answer from @maxjvh
Array(rows).fill().map(_ => Array(columns).fill(value))
- Another alternative simple way without using the
.map()
method
Array.from({ length: rows }, () => Array(columns).fill(value));
- Nested Loops
const array = [];
for (let i = 0; i < rows; i++) {
const row = [];
for (let j = 0; j < columns; j++) {
row.push(value);
}
array.push(row);
}
- Flat Array with Index Calculation
(This one is not a 2D array but is an alternative representation of a 2D space)
function create2DArrayAs1D(rows, columns) {
return new Array(rows * columns).fill(0);
}
function getElement(array, row, column, columns) {
return array[row * columns + column];
}
function setElement(array, row, column, value, columns) {
array[row * columns + column] = value;
}