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

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of Numbers. Our function should return a new array that contains all the elements from the original array that are greater than the cumulative sum of all elements up to that point. We are required to solve this problem using the Array.prototype.reduce() function.


Let’s write the code for this function −

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;


The output in the console −

[1, 2, 30]
Published on 12-Oct-2020 11:13:27