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]}`);
}
}iis the row index,jis the column index.matrix[i][j]is the element at rowi, columnj.
Output:
javascript
matrix[0][0] = 1
matrix[0][1] = 2
...
matrix[2][2] = 92. With for...of (more convenient and shorter)
javascript
for (const row of matrix) {
for (const value of row) {
console.log(value);
}
}- The outer
for...ofiterates 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
breakorreturn(unlikefor).
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); // 45The inner reduce sums a row, the outer one sums everything together.
In short:
| Way | What it does | Can the loop be interrupted |
|---|---|---|
for | Full control, indexes | Yes |
for...of | Simple and readable iteration | Yes |
forEach() | Functional style | No |
flat() + forEach() | Iterates all values as a one-dimensional array | No |
reduce() | Aggregation (for example, a sum) | Yes (logically) |
Summary: To iterate a two-dimensional array:
javascriptfor (const row of matrix) { for (const value of row) { console.log(value); } }is the modern, readable and safe way.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.