Skip to main content

How to iterate a two-dimensional array?

Iterating a two-dimensional array (or a matrix) is one of the basic but very important operations in programming. Since it is an array of arrays, it must be traversed with nested loops: the outer one over rows, the inner one over columns.


Example of a two-dimensional array:

javascript
const matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ];

1. The classic way with for

javascript
for (let i = 0; i < matrix.length; i++) { for (let j = 0; j < matrix[i].length; j++) { console.log(`matrix[${i}][${j}] = ${matrix[i][j]}`); } }
  • i is the row index,
  • j is the column index.
  • matrix[i][j] is the element at row i, column j.

Output:

javascript
matrix[0][0] = 1 matrix[0][1] = 2 ... matrix[2][2] = 9

2. With for...of (more convenient and shorter)

javascript
for (const row of matrix) { for (const value of row) { console.log(value); } }
  • The outer for...of iterates over the rows,
  • The inner one over the elements within a row.

The most readable and modern way to iterate.


3. With forEach()

javascript
matrix.forEach((row, i) => { row.forEach((value, j) => { console.log(`matrix[${i}][${j}] = ${value}`); }); });
  • Does not require indexes in the classic form,
  • Fits a more "functional" style,
  • But you cannot break the loop with break or return (unlike for).

4. With flat() (if you need to iterate all elements in a row)

javascript
matrix.flat().forEach(value => console.log(value));

flat() turns a two-dimensional array into a regular one-dimensional array:

javascript
matrix.flat(); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

5. With reduce() (for counting)

If you need, for example, to sum all the elements:

javascript
const sum = matrix.reduce( (acc, row) => acc + row.reduce((a, b) => a + b, 0), 0 ); console.log(sum); // 45

The inner reduce sums a row, the outer one sums everything together.


In short:

WayWhat it doesCan the loop be interrupted
forFull control, indexesYes
for...ofSimple and readable iterationYes
forEach()Functional styleNo
flat() + forEach()Iterates all values as a one-dimensional arrayNo
reduce()Aggregation (for example, a sum)Yes (logically)

Summary: To iterate a two-dimensional array:

javascript
for (const row of matrix) { for (const value of row) { console.log(value); } }

is the modern, readable and safe way.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.