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
From an array of arrays, return an array where each item is the sum of all the items in the corresponding subarray in JavaScript
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 we have nested arrays with numbers, we want to calculate the sum of each inner array and return those sums as a new array.
Example Input and Expected Output
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:
[10, 18, 50]
Using reduce() Method
We can solve this using the reduce() method to sum elements within each subarray and build the result array:
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));
[ 10, 18, 50 ]
Using map() Method (Alternative Approach)
A cleaner approach is using map() since we're transforming each subarray into a single sum:
const numbers = [
[1, 2, 3, 4],
[5, 6, 7],
[8, 9, 10, 11, 12]
];
const sumSubArrays = arr => {
return arr.map(subArray =>
subArray.reduce((sum, num) => sum + num, 0)
);
};
console.log(sumSubArrays(numbers));
[ 10, 18, 50 ]
How It Works
Both approaches iterate through the main array:
-
Method 1: Uses
reduce()to build a new array by pushing sums -
Method 2: Uses
map()to transform each subarray directly into its sum
The inner reduce() calculates the sum of each subarray by accumulating all numbers starting from 0.
Conclusion
Both methods work effectively, but map() is more semantic since we're transforming arrays. Use reduce() with an initial value of 0 to safely handle empty subarrays.
