CodeBlanks Logo Icon CodeBlanks

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.

Practice 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.

Starter code

script.js
// Create the nested array

// Print the element at row 1, column 2

Sample solution

script.js
const matrix = [[1, 2, 3], [4, 5, 6]];
console.log(matrix[1][2]);

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What value does <code>grid[2][1]</code> return?

script.js
const grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
  • 2
  • 5
  • 8 Correct answer
  • 6

Explanation: grid[2] is the third row [7, 8, 9]; grid[2][1] returns 8.

2 Access a cell with grid[1][2]

Question
const grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const cell = grid[1][____];
console.log(cell);
Answer
const grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const cell = grid[1][2];
console.log(cell);

Explanation: grid[1][2] = 6 (third element of the second row).

3 Match expressions for <code>const grid = [[1, 2, 3], [4, 5, 6]]</code>

Term Meaning
grid.length 2
grid[0] [1, 2, 3]
grid[1][0] 4
grid[0][2] 3

All lessons in Beginner