Arrays of Arrays
A multidimensional array is an array that contains other arrays.
This is common for grids, tables, and matrices.
JavaScript Tutorial
Multidimensional arrays are arrays of arrays and are common in grid or table data.
They require two indexes to access individual elements.
Many problems involve grids, boards, or matrices. Multidimensional arrays model them directly.
Understanding access and iteration patterns makes these problems easier.
const grid = [[1, 2], [3, 4]]
grid[row][col]const grid = [
[1, 2],
[3, 4],
];
console.log(grid[0][1]); // 2Access row 0, column 1.
const grid = [
[1, 2],
[3, 4],
];
for (let r = 0; r < grid.length; r++) {
for (let c = 0; c < grid[r].length; c++) {
console.log(grid[r][c]);
}
}Use nested loops for traversal.
A multidimensional array is an array that contains other arrays.
This is common for grids, tables, and matrices.
Use two indexes to access row and column positions.
grid[row][col] is the typical pattern.
Use nested loops to iterate through rows and columns.
Keep the inner loop simple for performance.
Without
const row0col1 = grid[0][1];With
const row0col1 = grid[0][1]; // direct accessRows can have different lengths; check before indexing.
Be consistent with grid[row][col].
Extract helper functions for clarity.
Use nested loops for rows and columns.
Yes, use flat() or reduce with concat.
No, arrays can be jagged.
Practice: Print all values of a 2x2 grid using nested loops.
const grid = [[1, 2], [3, 4]];
// TODO: print all values
One Possible Solution
const grid = [[1, 2], [3, 4]];
for (let r = 0; r < grid.length; r++) {
for (let c = 0; c < grid[r].length; c++) {
console.log(grid[r][c]);
}
}An array that contains other arrays.
Use two indexes: grid[row][col].
Yes, JavaScript arrays are not required to be rectangular.
Try changing values and indexes in the grid.