Two Dimensional Arrays

Open the project folder

In our starter files, open the index.html page from this lessons folder:

02.Arrays-In-More-Depth > 10.Two-dimensional-arrays

Structure of a two dimensional array

Regular arrays store values in order from left to right, starting at the index position of zero. But we can also use arrays in a two-dimensional way to create a grid like structure. Seems complex right?

This is not as complex as it may seem, all we are really doing is creating a new array for each row:

multiple arrays in a grid

The first row is an array, the second row is an array and so on. Then we place all of these, inside of another array. Creating an array of arrays.

Selecting values

Accessing these values is simple, we just need two index numbers. First select the row, and then we select the index from that row.

We use these 2 numbers to select any one of these values we need:

selecting values from two dimensional arrays

JavaScript does not have a built-in way of creating two dimensional arrays, instead we construct them by adding arrays inside of another array.

Let’s give this a try:

let grid = [
  [11, 12, 13, 14],
  [21, 22, 23, 24],
  [31, 32, 33, 34],
];
console.log(grid);

We can open the main array in the console, then into each nested array. And you may find it easier view with a console.table:

console.table(grid);

As with the images above, we then use two index positions to access single values. First the row, then the index number from that row:

console.log(grid[2][1]);