From an array of arrays, return an array where each item is the sum of all the items in the corresponding subarray in JavaScript



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 ]
Updated on: 2020-08-28T14:03:26+05:30

316 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements