# Iterate multidimensional arrays using for loop

Hi,
I understand that the code below evaluates the product of a simple array

var arr = [[2,3],[2,3]];
var product = 1;

For (i=0; i<arr.length; i++) {
For (j=0; j<arr[i].length; j++) {
product *=arr[i][j];
}
}

How would you get the product of an array like this:
[[2,3,[2,3]], [2,3], [2,3]]?
I’ve tried this, but it doesn’t work.

var arr =[[2,3,[2,3]], [2,3], [2,3]];
var product = 1;

For (i=0; i<arr.length; i++) {
For (j=0; j<arr[i].length; j++) {
For (k=0; k<arr[j].lenght; k++) {
product *=arr[i][j][k];
}
}
}

1 Like

I guess it’s because you need loop through the index of the array within the array and not just the array.

In your case, you need to loop through `arr[i][j]`.

``````var arr =[[2,3,[2,3]], [2,3], [2,3]];

var product = 1;

for (i=0; i<arr.length; i++) {
for (j=0; j<arr[i].length; j++) {
for (k=0; k<arr[i][j].length; k++) {
product *=arr[i][j][k];
}}
}
console.log(product)
``````

The loop does iterate through all elements but the product will not be a sum of all elements in the array; it will only total up the third dimension elements (note: the deepest elements within the array).

This is because `arr`'s structure is not uniform i.e an element is three dimensional, others are two dimensional. You’ll have to devise the the logic required to sum up values in all dimensions.

That’s the best explanation I can come up with. Someone else can explain better.

Alright. I’ll try using this explanation to tweak it. Thanks

1 Like