Multidimensional arrays
Learn to create matrix-like structures with nested arrays.
Nested arrays
The elements of an array can themselves be arrays. This is called a nested array. It is used to store data shaped like a two-dimensional grid.
Example: const grid = [[1, 2, 3], [4, 5, 6]]; is a matrix with two rows. The first row is grid[0], the second row is grid[1].
To access a cell you use two indices: grid[0][1] returns the second element of the first row (2).
Traversing with nested loops
To traverse a nested array you use a nested for loop. The outer loop visits rows, the inner loop visits columns.
Example: for (let i = 0; i < grid.length; i++) { for (let j = 0; j < grid[i].length; j++) { console.log(grid[i][j]); } } prints every cell in order.
grid.length gives the row count, grid[i].length gives the column count of one row. In a regular matrix these are the row and column counts.
Exercise Print a cell from the matrix array
Create a nested array named matrix with at least two rows. Each row must hold at least three numbers. Then print the third element of the second row (matrix[1][2]) with console.log.
Show example solution
Define a matrix array with two rows of three numbers, then print matrix[1][2].
Example solution:
const matrix = [[1, 2, 3], [4, 5, 6]];
console.log(matrix[1][2]);
Test yourself
-
What value does <code>grid[2][1]</code> return?
const grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];- 2
- 5
- 8
- 6
Show answer
8 — Correct. grid[2] is the third row [7, 8, 9]; grid[2][1] returns 8.
-
Access a cell with grid[1][2]
const grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; const cell = grid[1][____]; console.log(cell);Show answer
const grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; const cell = grid[1][2]; console.log(cell); -
Match expressions for <code>const grid = [[1, 2, 3], [4, 5, 6]]</code>
- grid.length
- 2
- grid[0]
- [1, 2, 3]
- grid[1][0]
- 4
- grid[0][2]
- 3