To create a Two Dimensional Array in JavaScript, you can initialize an array of arrays with specified dimensions.
In this example,
matrix
with dimensions 3x3.const matrix = new Array(3);
for (let i = 0; i < matrix.length; i++) {
matrix[i] = new Array(3);
for (let j = 0; j < matrix[i].length; j++) {
matrix[i][j] = i + j;
}
}
console.log(matrix);
[ [ 0, 1, 2 ], [ 1, 2, 3 ], [ 2, 3, 4 ] ]
In this example,
matrix
with dimensions 2x2.const matrix = new Array(2);
for (let i = 0; i < matrix.length; i++) {
matrix[i] = new Array(2);
for (let j = 0; j < matrix[i].length; j++) {
matrix[i][j] = `Row ${i + 1}, Column ${j + 1}`;
}
}
console.log(matrix);
[ [ 'Row 1, Column 1', 'Row 1, Column 2' ], [ 'Row 2, Column 1', 'Row 2, Column 2' ] ]
In this tutorial, we learned How to create a Two Dimensional Array in JavaScript language with well detailed examples.