Menu
Coddy logo textTech

Nested Loops with 2D Arrays

Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 8 of 65.

When working with 2D arrays, we often use nested loops to iterate over each row and each column, allowing us to access or modify every element in the array.

Here's a typical structure of nested loops for a 2D array:

const seats = [
  [true, true, false],
  [true, false, true]
];

for (let r = 0; r < seats.length; r++) {
  // Outer loop iterates over rows
  for (let c = 0; c < seats[r].length; c++) {
    // Inner loop iterates over columns
    // seats[r][c] can be accessed here
  }
}

The outer loop iterates over the rows, and the inner loop iterates over the columns of each row. This way, you can access each element in the 2D array by using array[r][c].

challenge icon

Challenge

Easy

Create a function named countOccurrences that takes a 2D array of strings matrix and a string target. It should return how many times target appears across all rows and columns.

Cheat sheet

Use nested loops to iterate over 2D arrays - the outer loop for rows and inner loop for columns:

const seats = [
  [true, true, false],
  [true, false, true]
];

for (let r = 0; r < seats.length; r++) {
  // Outer loop iterates over rows
  for (let c = 0; c < seats[r].length; c++) {
    // Inner loop iterates over columns
    // Access element with seats[r][c]
  }
}

Try it yourself

function countOccurrences(matrix, target) {
  // TODO: Implement logic to count how many times 'target' appears in matrix
}
// Do not write anything outside function
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow