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

JavascriptWeb DevelopmentObject Oriented Programming

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 ]
raja
Published on 28-Aug-2020 14:02:56
Advertisements