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.
Example
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; } console.log(retainGreaterElements(arr));
Output
The output in the console −
[1, 2, 30]