Honestly, the easiest way that comes to mind would be to use to flatten the array and then multiply the contents. There is a later change on using recursion to flatten arrays if you wanted to use only loops and recursion to do it instead of built-in methods.
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.
@JeremyLT is right. If you don’t know in advance how nested your array is, you need a more complicated solution. There are array methods (like flat and reduce) that handle a lot of the messy parts of operations like this for real-world use.
As said it can quickly become a bit of a hardcoded solution if it is just written for that specific case.
You can check if arr[i][j] is an array, if it is, loop it and do the multiplication of arr[i][j][k], otherwise do the multiplication of arr[i][j].
This might just be garbage code, it definitely is ugly, but it seems to work. I haven’t written a for loop this nested in some time (I can barely remember the last time I wrote a for loop).
const arr = [
[2, 3, [2, 3], 5],
[[2, 3], 2, 3],
[2, 3],
];
var product = 1;
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
if (Array.isArray(arr[i][j])) {
for (let k = 0; k < arr[i][j].length; k++) {
product *= arr[i][j][k];
}
} else {
product *= arr[i][j];
}
}
}
console.log(product); // 38880
Thanks. I can see that you multiplied the deepest nested arrays first (cause .isarray will be true) . The product then serves as the base value for the next multiplication. Really appreciate your time. I’ll look more into it. Then if possible, try to produce a modified solution.
Update for anyone who cares
Here’s a much simpler and straightforward way.
let array = [[1, 2 , [5, 6]], [3, 4]];
let arrayFlat = array.flat(Infinity) //Flatten multidimensional array of any depth. Infinity is the depth.
//you can now perform anything on the flattened array
let product = arrayFlat.reduce((acc, value) => acc * value, 1)
To be fair, the title of the thread is Iterate through multidimensional arrays using for loop, which you are not doing. You are just flattening the arrays. Not saying it’s a bad choice, just that it isn’t really what was asked for in the thread.
Yes I understand that it’s not what was asked. I just wanted to share this to show that it could be done much easily “for anyone who cared know”. Using For loop can become very complex especially if the depths of the nested arrays are not uniform. Thanks for your input.