Two dimensional array is commonly known as array of arrays. It is very useful in mathematics while working with matrix or grid. There are different approaches to create two dimensional array in JavaScript, these are -
Creating a 2D Array in JavaScript
A 2D array is created by nesting arrays within another array. Each nested array represents a "row," and each element within a row represents a "column."
JavaScript 2D Array1. Using Array Literal Notation - Most used
The basic method to create two dimensional array is by using literal notation [].
Syntax
const mat = [ [ num11, num12, ... ], [ num21, num22, ... ], ... ]
JavaScript
let mat = [
[ 10, 20, 30 ],
[ 40, 50, 60 ],
[ 20, 50, 70 ]
];
console.log(mat);
Output[ [ 10, 20, 30 ], [ 40, 50, 60 ], [ 20, 50, 70 ] ]
2. Using Array.from() Method
The JavaScript Array from() method returns an Array object from any object with a length property or an iterable object.
Syntax
const mat = Array.from({ length: rows }, () => new Array(columns).fill(0));
JavaScript
const rows = 3;
const cols = 4;
const mat = Array.from({ length: rows }, () => new Array(cols).fill(0));
console.log(mat);
Output[ [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ] ]
3. Using Nested For Loop
We can also use nested for loop to create a 2D array. The loop will iterate rows * cols times.
JavaScript
let mat = [];
let rows = 3;
let cols = 3;
let val = 0
for (let i = 0; i < rows; i++) {
mat[i] = [];
for (let j = 0; j < cols; j++) {
mat[i][j] = val++;
}
}
console.log(mat);
Output[ [ 0, 1, 2 ], [ 3, 4, 5 ], [ 6, 7, 8 ] ]
4. Using Array.fill() Method
In this approach, we will use the fill() method and map method for creating the two-dimensional array in JavaScript.
Example: This example shows the implementation of above-explained approach.
JavaScript
const rows = 3;
const cols = 4;
const mat = Array(rows).fill().map(() => Array(cols).fill(0));
console.log(mat);
Output[ [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ] ]
Accessing Elements in a 2D Array
You can access elements in a 2D array using two indices: the row index and the column index. Remember that JavaScript uses zero-based indexing.
JavaScript
let mat = [
[10, 20, 30],
[40, 50, 60],
[70, 80, 90]
];
console.log(mat[0][1]);
console.log(mat[2][0]);
Modifying Elements in a 2D Array
You can modify specific elements in a 2D array by accessing them with their indices and assigning a new value.
JavaScript
let mat = [
[10, 20, 30],
[40, 50, 60],
[70, 80, 90]
];
mat[1][2] = 100;
console.log(mat);
Output[ [ 10, 20, 30 ], [ 40, 50, 100 ], [ 70, 80, 90 ] ]