Retaining array elements greater than cumulative sum using reduce() in JavaScript

We need to write a JavaScript function that takes an array of numbers and returns a new array containing only elements that are greater than the cumulative sum of all previous elements. We'll solve this using the Array.prototype.reduce() method.

Problem Understanding

For each element in the array, we compare it with the sum of all elements that came before it. If the current element is greater than this cumulative sum, we include it in the result array.

Example

Let's implement the solution using reduce():

const arr = [1, 2, 30, 4, 5, 6];

const retainGreaterElements = arr => {
    let res = [];
    arr.reduce((acc, val) => {
        return (val > acc && res.push(val), acc + val);
    }, 0);
    return res;
}

console.log(retainGreaterElements(arr));
[1, 2, 30]

How It Works

The function works as follows:

  • Element 1: 1 > 0 (cumulative sum) ? ? Include in result
  • Element 2: 2 > 1 (cumulative sum) ? ? Include in result
  • Element 30: 30 > 3 (cumulative sum) ? ? Include in result
  • Element 4: 4 > 33 (cumulative sum) ? ? Skip
  • Element 5: 5 > 37 (cumulative sum) ? ? Skip
  • Element 6: 6 > 42 (cumulative sum) ? ? Skip

Alternative Implementation

Here's a cleaner version that separates the logic more clearly:

const retainGreaterElementsClean = arr => {
    const result = [];
    
    arr.reduce((cumulativeSum, currentElement) => {
        if (currentElement > cumulativeSum) {
            result.push(currentElement);
        }
        return cumulativeSum + currentElement;
    }, 0);
    
    return result;
};

const testArray = [5, 1, 10, 3, 8];
console.log(retainGreaterElementsClean(testArray));
[5, 10, 8]

Key Points

  • The reduce() method maintains a running cumulative sum as the accumulator
  • Each element is compared against the sum of all previous elements
  • The comma operator in the original solution allows multiple operations in the return statement
  • The accumulator always gets updated with the current element, regardless of whether it's included in the result

Conclusion

Using reduce() provides an elegant solution for filtering array elements based on cumulative sum comparison. The key insight is using the accumulator to track the running sum while building the result array separately.

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

202 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements