Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to sum elements at the same index in array of arrays into a single array? 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]
Let's explore different approaches to solve this problem.
Using forEach() Method
The most straightforward approach is to iterate through each sub-array and accumulate values at corresponding indices:
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 ]
Using reduce() Method
A more functional approach using reduce() to accumulate the sums:
const arr = [
[43, 2, 21],[1, 2, 4, 54],[5, 84, 2],[11, 5, 3, 1]
];
const sumArrayReduce = (array) => {
return array.reduce((acc, current) => {
current.forEach((num, index) => {
acc[index] = (acc[index] || 0) + num;
});
return acc;
}, []);
}
console.log(sumArrayReduce(arr));
[ 60, 93, 30, 55 ]
Using map() with Maximum Length
This approach first determines the maximum array length, then maps over each index:
const arr = [
[43, 2, 21],[1, 2, 4, 54],[5, 84, 2],[11, 5, 3, 1]
];
const sumArrayMap = (array) => {
const maxLength = Math.max(...array.map(subArray => subArray.length));
return Array.from({length: maxLength}, (_, index) => {
return array.reduce((sum, subArray) => {
return sum + (subArray[index] || 0);
}, 0);
});
}
console.log(sumArrayMap(arr));
[ 60, 93, 30, 55 ]
How It Works
All methods follow the same logic:
- Iterate through each sub-array in the main array
- For each element at index
i, add it to the result array at the same indexi - If the result array doesn't have a value at index
i, initialize it with the current element - If it already has a value, add the current element to the existing sum
Comparison
| Method | Readability | Performance | Functional Style |
|---|---|---|---|
| forEach() | High | Good | No |
| reduce() | Medium | Good | Yes |
| map() with max length | Medium | Lower (calculates max first) | Yes |
Conclusion
The forEach() approach is the most readable for beginners, while reduce() offers a more functional programming style. Choose the method that best fits your coding preferences and team standards.
