Given an array of arrays, each of which contains a set of numbers. We have to write a function that returns an array where each item is the sum of all the items in the corresponding subarray.
For example −
If the input array is −
const numbers = [ [1, 2, 3, 4], [5, 6, 7], [8, 9, 10, 11, 12] ];
Then output of our function should be −
const output = [10, 18, 50];
So, let’s write the code for this function −
Example
const numbers = [
[1, 2, 3, 4],
[5, 6, 7],
[8, 9, 10, 11, 12]
];
const sum = arr => arr.reduce((acc, val) => acc+val);
const sumSubArray = arr => {
return arr.reduce((acc, val) => {
const s = sum(val);
acc.push(s);
return acc;
}, []);
};
console.log(sumSubArray(numbers));Output
The output in the console will be −
[ 10, 18, 50 ]