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
Return the largest array between arrays JavaScript
We have an array of arrays that contains some numbers, we have to write a function that takes in that array and returns the index of the subarray that has the maximum sum. If more than one subarray has the same maximum sum, we have to return the index of first such subarray.
Problem Overview
Given multiple arrays nested within a main array, we need to:
- Calculate the sum of each subarray
- Find which subarray has the largest sum
- Return the index of that subarray
Solution Using reduce() Method
We can solve this by using the reduce() method to iterate through the array and track both the maximum sum and its corresponding index.
const arr = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]];
const findMaxSubArray = (arr) => {
const add = (array) => array.reduce((acc, val) => acc + val);
return arr.reduce((acc, val, ind) => {
const sum = add(val);
if (sum > acc.sum) {
return {
index: ind,
sum
}
}
return acc;
}, {
index: -1,
sum: -Infinity
}).index;
};
console.log(findMaxSubArray(arr));
3
How It Works
Let's break down the solution step by step:
-
Helper function:
add()calculates the sum of any array usingreduce() -
Main logic: We use
reduce()on the main array to compare sums - Accumulator: Tracks the current maximum sum and its index
-
Initial value:
{index: -1, sum: -Infinity}ensures any real sum will be larger
Alternative Approach Using for Loop
Here's a more straightforward approach using a traditional loop:
const arr = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]];
const findMaxSubArraySimple = (arr) => {
let maxSum = -Infinity;
let maxIndex = -1;
for (let i = 0; i < arr.length; i++) {
const currentSum = arr[i].reduce((sum, num) => sum + num, 0);
if (currentSum > maxSum) {
maxSum = currentSum;
maxIndex = i;
}
}
return maxIndex;
};
console.log(findMaxSubArraySimple(arr));
3
Step-by-Step Calculation
For the given example array, here's how the sums are calculated:
const arr = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]];
arr.forEach((subarray, index) => {
const sum = subarray.reduce((acc, val) => acc + val, 0);
console.log(`Index ${index}: [${subarray.join(', ')}] = ${sum}`);
});
Index 0: [4, 5, 1, 3] = 13 Index 1: [13, 27, 18, 26] = 84 Index 2: [32, 35, 37, 39] = 143 Index 3: [1000, 1001, 857, 1] = 2859
Comparison of Methods
| Method | Readability | Performance | Functional Style |
|---|---|---|---|
| reduce() with helper | Complex | Good | Yes |
| for loop | Simple | Good | No |
Conclusion
Both approaches effectively find the index of the subarray with the maximum sum. The reduce() method offers a functional programming style, while the for loop provides better readability for beginners.
