Column sum of elements of 2-D arrays in JavaScript

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]

This means we add all elements at index 0 (43+1+5+11=60), all elements at index 1 (2+2+84+5=93), and so on.

Using forEach Method

Let's write the function sumArray() using nested forEach loops:

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));
[ 60, 93, 30, 55 ]

Here we iterate over each sub-array and then each number, checking if the sum at that index already exists. If it does, we add the current number to it; otherwise, we initialize it with the current number.

Using for...of Loops

An alternative approach using for...of loops for better readability:

const arr = [
   [43, 2, 21],
   [1, 2, 4, 54],
   [5, 84, 2],
   [11, 5, 3, 1]
];

const sumArrayForOf = (array) => {
   const result = [];
   
   for (let subArray of array) {
      for (let i = 0; i 

[ 60, 93, 30, 55 ]

Using reduce Method

A more functional approach using the reduce method:

const arr = [
   [43, 2, 21],
   [1, 2, 4, 54],
   [5, 84, 2],
   [11, 5, 3, 1]
];

const sumArrayReduce = (array) => {
   return array.reduce((acc, subArray) => {
      subArray.forEach((num, index) => {
         acc[index] = (acc[index] || 0) + num;
      });
      return acc;
   }, []);
}

console.log(sumArrayReduce(arr));
[ 60, 93, 30, 55 ]

Comparison

Method Readability Performance Best For
forEach Good Fast Beginners
for...of Excellent Fast Clear logic
reduce Good Moderate Functional programming

Conclusion

All three methods effectively calculate column sums of 2D arrays. The for...of approach offers the best balance of readability and performance for most use cases.

Updated on: 2026-03-15T23:19:00+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements