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
EasyCreate 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 functionThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String FundamentalsIterate Over StringsTemplate LiteralsString MethodsRecap - String Weaver4JSON Part 2
Iterate Over JSONNested JSONJSON Optional ChainingShallow And Deep CopyRecap - Bicycle ShopRecap - Solar System10Manage Festival System
Project OverviewAdd Movies & Venues2Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays5Sets Part 1
What Is A Set?Iterating Over SetsAdding An ElementRemoving An ElementChecking If An Element ExistsSize And Is EmptyCopy And ClearRecap - Basic Of Sets8Arrays Interesting Topics
Array DestructuringSpread Syntax in ArraysSparse ArraysRecap - Arrays Workshop3JSON Part 1
What is a JSON?Check If Key ExistsObject MethodsThe Spread Operator Part 1The Spread Operator Part 2Remove KeysRecap - JSON Manipulate Keys