Column sum of elements of 2-D arrays in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject 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]
]

Output

Then the output should be −

[60, 93, 30, 55]

Let’s write the function addArray() −

Example

The full code for this function will be −

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));

Here 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.

Output

The output in the console will be −

[ 60, 93, 30, 55 ]
raja
Published on 17-Oct-2020 14:50:18
Advertisements