1

I am trying to multiply child array elements. Can you please have a look below code and let me know if we can do more optimization.

Note:- I want to push the multiplied value of child arrays in another array.

Can you please help me with this.

var arr1 = [
    [3, 2],
    [2, 3],
    [4, 5]
]

var sumArr = [];
for (var row = 0; row < arr1.length; row++) {
    var fullRow = arr1[row];
    var val = 1;
    for (var col = 0; col < fullRow.length; col++) {
        val *= fullRow[col];
    }
    sumArr.push(val);

}
console.log(sumArr);
3
  • 1
    What do you mean by "optimization"? Commented Dec 18, 2018 at 19:19
  • This is related to javascript Commented Dec 19, 2018 at 0:43
  • What is the expected output? Does this code work? Commented Dec 19, 2018 at 0:45

1 Answer 1

1

The best way to do this would be to use map and reduce as follows:

const arr1 = [ [3, 2]
             , [2, 3]
             , [4, 5]
             ];

const multiply = (a, b) => a * b;

const product = arr => arr.reduce(multiply, 1);

const sumArr = arr1.map(product);

console.log(sumArr);

I'm not sure what you mean by "optimization" but is this what you're looking for?

Sign up to request clarification or add additional context in comments.

5 Comments

This doesn't deal well with an edge case of [] as it will return 1 instead of 0
It's supposed to return 1 because that is the identity element of multiplication. It's not supposed to return 0 because that is the absorbing element of multiplication.
The multiplication of no elements is 1?
If you asked me what is the product of nothing I would answer nothing.
For multiplication 1 is "nothing". The "nothing" that you are referring to is the identity element. This makes sense because when you convert numbers into their logarithms then multiplication becomes addition and 1 becomes 0. However, 0 becomes undefined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.