Essential JavaScript

Going Further

Arrays of Arrays

Arrays can contain any values, including other arrays.

An array that contains other arrays is a multidimensional array.

Multidimensional arrays are used to represent tables and other grid structures.

You may have played a video game that used a tile map grid. Such maps are stored as two-dimensional arrays.

Creating a 2D array

To create a 2D array, you can first create the individual arrays that will go inside the main array:

const row1 = [1, 2, 3]; const row2 = [4, 5, 6]; const row3 = [7, 8, 9] const grid = [row1, row2, row3]; console.log(grid);

The above example clearly shows the individual row arrays and the grid that contains each row.

We could also define the 2D grid array all at once:

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

Accessing values

Accessing values in a 2D array is much like accessing the values in a flat array.

We use bracket notation to get a value at a particular index:

  • The first set of brackets will return one of the arrays inside the main array.
  • The second set of brackets will return a value from that inner array.
const grid = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ]; const row1 = grid[0]; console.log(row1); // [1, 2, 3] const row1cell1 = grid[0][0]; console.log(row1cell1); // 1 const row3cell2 = grid[2][1]; console.log(row3cell2); // 8

Iterate a 2D array

Iterating through all the elements of a 2D array requires two nested for loops:

const grid = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ]; for (let rowIndex = 0; rowIndex < grid.length; rowIndex++) { const row = grid[rowIndex]; for (let cellIndex = 0; cellIndex < row.length; cellIndex++) { const cell = row[cellIndex]; console.log(rowIndex, cellIndex, cell); } }

Learning Goals

  • I can create a 2D array

  • I can get a value from any position in a 2D array

  • I can iterate over all values in a 2D array

Code Editor

Click "Run Code" to execute your JavaScript in a secure sandbox and see the output below.

Console Output

// Console output will appear here...

0 output lines