I am trying to write a function called twoDimensionalProduct(array)
that takes in a 2D array of
numbers as an argument. The function should return the total product of all
numbers multiplied together.
I can solve this using nested traditional for loops. This was my solution:
function twoDimensionalProduct(array){
let prod = 1;
for(let i = 0; i < array.length; i ){
let subArr = array[i];
for(let j = 0; j < subArr.length; j ){
prod *= subArr[j]
}
}
return prod
}
let arra1 = [
[6, 4],
[5],
[3, 1]
];
console.log(twoDimensionalProduct(arra1)); // 360
I am trying to figure out how to solve the same problems using the forEach or reduce method. Can someone help me with the best approach to this?
CodePudding user response:
If you like one liners, here's how you do it in one line.
let arra1 = [
[6, 4],
[5],
[3, 1]
];
let sum = arra1.flat(2).reduce((sum, val) => sum * val);
console.log(sum);
CodePudding user response:
Flatten the array and then reduce
over the numbers.
function twoDimensionalProduct(array){
return array.flat().reduce((acc, c) => acc * c);
}
let arra1 = [[6, 4],[5],[3, 1]];
console.log(twoDimensionalProduct(arra1));
CodePudding user response:
You can map the array to multiply within elements using reduce and finally reduce on the outer array
const prod = arra1.map((arr) => {
return arr.reduce((a, b) => a * b);
}).reduce((a, b) => a * b);
console.log(prod);