2d arrays

A.k.a. arrays of arrays

Arrays can be of anything

const ss = [ 'foo', 'bar', 'baz' ]; // array of strings
const ns = [ 1, 2, 3 ]; // array of nummers

Well …

const grid = [ [ 1, 2 ], [ 3, 4 ] ];

An array of arrays

For example

const ticTacToe = [
  [ 'X', 'O', 'O' ],
  [ 'O', 'X', '' ],
  [ 'X', '', 'O' ],
];

» ticTacToe[0]
['X', 'O', 'O']

» ticTacToe[0][0]
'X'

Accessing and setting

ticTacToe[0][1] = 'O'

ticTacToe[0][1] ⟹ 'O'

Looping over a row of a 2d array

const row = ticTacToe[0]; // zeroth row
for (let c = 0; c < row.length; c++) {
   console.log(row[c]); // let's log what's there
}

This is just a regular loop over a 1d array.

Looping over a column of a 2d array

const c = 0; // column 0
for (let r = 0; r < ticTacToe.length; r++) {
   console.log(ticTacToe[r][c]); // let's log what's there
}

The columns are made up of one element from each row of the 2d array.

Looping over every cell of a 2d array

for (let r = 0; r < ticTacToe.length; r++) {
  for (let c = 0; c < ticTacToe[0].length; c++) {
    ticTacToe[r][c] = '';
  }
}

Loops through every element of the 2d array, setting it to the empty strincg.