How to sum elements at the same index in array of arrays into a single array? JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

We have an array of arrays and are required to write a function that takes in this array and returns a new array that represents the sum of corresponding elements of original array.

If the original array is −

[
   [43, 2, 21],[1, 2, 4, 54],[5, 84, 2],[11, 5, 3, 1]
]

Then the output should be −

[60, 93, 30, 55]

Let’s write a sample function addArray()

The full code for this function will be −

Example

const arr = [
   [43, 2, 21],[1, 2, 4, 54],[5, 84, 2],[11, 5, 3, 1]
];
const sumArray = (array) => {
   const newArray = [];
   array.forEach(sub => {
      sub.forEach((num, index) => {
         if(newArray[index]){
            newArray[index] += num;
         }else{
            newArray[index] = num;
         }
      });
   });
   return newArray;
}
console.log(sumArray(arr));

Output

The output in the console will be −

[ 60, 93, 30, 55 ]

Above, we iterate over each element of the original array and then each number, checking if the sum of that index already existed, we just added the corresponding number to it othewise we set the corresponding num equal to it.

raja
Published on 19-Aug-2020 07:01:14
Advertisements