Arrays Inside Arrays

Grade 7, page 12 of 14. A one-minute read.

An array can contain other arrays! This is perfect for anything that's shaped like a grid: a game board, a spreadsheet, a seating plan, a map.

Here's a tic-tac-toe board:

JavaScript
const board = [
  ["X", "O", "X"],
  ["O", "X", "O"],
  ["O", "X", "X"],
];

console.log(board[0]);
console.log(board[1][1]);
console.log(board[2][0]);

It prints

[ 'X', 'O', 'X' ]
X
O

board[0] is the first row (itself an array). board[1][1] means "row 1, then column 1": the center square. Two sets of square brackets, two steps: first pick the row, then pick the item in that row.

To visit every square, use a nested loop (Grade 5): an outer loop for the rows and an inner loop for the columns:

JavaScript
for (const row of board) {
  console.log(row.join(" | "));
}

let xCount = 0;
for (let r = 0; r < board.length; r++) {
  for (let c = 0; c < board[r].length; c++) {
    if (board[r][c] === "X") {
      xCount++;
    }
  }
}
console.log(`X appears ${xCount} times.`);

It prints

X | O | X
O | X | O
O | X | X
X appears 5 times.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning