Iterating the elements of two-dimensional arrays

If we want to verify the output of the matrix, we can create a generic function to log its output:

function printMatrix(myMatrix) { 
  for (let i = 0; i < myMatrix.length; i++) { 
    for (let j = 0; j < myMatrix[i].length; j++) { 
      console.log(myMatrix[i][j]); 
    } 
  } 
} 

We need to loop through all the rows and columns. To do this, we need to use a nested for loop, in which the variable i represents rows, and j represents the columns. In this case, each myMatrix[i] also represents an array, therefore we also need to iterate each position of myMatrix[i] in the nested for loop.

We can output the contents of the averageTemp matrix using the following code:

printMatrix(averageTemp); 
To output a two-dimensional ...

Get Learning JavaScript Data Structures and Algorithms - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.