Sometimes, we want to loop through arrays of arrays with JavaScript.
In this article, we’ll look at how to loop through arrays of arrays with JavaScript.
How to loop through arrays of arrays with JavaScript?
To loop through arrays of arrays with JavaScript, we can use the for-of loop.
For instance, we write:
const printArray = (arr) => {
for (const a of arr) {
if (Array.isArray(a)) {
printArray(a);
} else {
console.log(a);
}
}
}
const parentArray = [
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
],
[
[10, 11, 12],
[13, 14, 15],
[16, 17, 18]
],
[
[19, 20, 21],
[22, 23, 24],
[26, 27, 28]
]
];
printArray(parentArray)
to define the printArray
function that takes the arr
array.
In it, we use the for-of loop to loop through each entry of arr
.
And in the loop body, we check if a
is an array with Array.isArray
.
If it’s an array, we call printArray
again.
Otherwise, we log the value with console.log
.
Therefore, when we call printArray
with parentArray
, we see all the values logged.
Conclusion
To loop through arrays of arrays with JavaScript, we can use the for-of loop.