How to get the product of each array in multidimensional array?

Hi

Here’s a multidimensional array
let a = [[1, 2], [3, 4], [5, 6]];

i want to multiply each array inside the multidimensional and get the product and not the product of the full ‘a’.

how can i get the product of each array? I want the output as 2 , 12, 30

1 Like

Hi! First post here so I hope I’m doing it right.

I think you can run a loop that adds them individuall;

let a = [[1, 2], [3, 4], [5, 6]];
let b = []

for (var i = 0; i < a.length; i++) {
 
    b.push(a[i][0] * a[i][1]);

}
console.log(b)

Good luck!

1 Like

Hey Hapiel, this solution works. Thank a lot. But now what if the array is somthing like this

let a = [[1, 2], [1, 2, 3, 55], [4, 3, 4, 2, 5]];

in this case what do we do? I tried using two for loops but i am not getting the result

What’s going wrong with the two loops?

This is my quick and dirty fix.

let a = [[1, 2], [1, 2, 3, 55], [4, 3, 4, 2, 5]];
let b = []
let c = 1

for (var i = 0; i < a.length; i++) {
 
    for (var j = 0; j < a[i].length; j++) {
      c *= a[i][j]
    }

    b.push(c);
    c = 1;


}
console.log(b)
1 Like
function multiplyAllNumbers(array){ 
// returns the product of numbers in a uni-dimensional array
    let product = 1
    for (let i = 0; i < array.length; i++){
        product = product * array[i] 
    }
    return product
}

function arrayOfProducts(array){
    let result = []
    for (let i = 0; i < array.length; i++){
        product = multiplyAllNumbers(array[i]) // apply multiply function to each item
        result.push(product)
    }
    return result
}
1 Like

i is a number, it will not work, the function expects an array as argument

It should be product = multiplyAllNumbers(array[i]);

Please edit your solution with this

It should be
product = multiplyAllNumbers(array[i]);