- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Retaining array elements greater than cumulative sum using reduce() in JavaScript
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]
- Related Articles
- Cumulative sum of elements in JavaScript
- Converting array of Numbers to cumulative sum array in JavaScript
- JavaScript reduce sum array with undefined values
- Finding element greater than its adjacent elements in JavaScript
- Find the number of elements greater than k in a sorted array using C++
- Mask array elements greater than a given value in Numpy
- Return the cumulative sum of array elements treating NaNs as zero in Python
- Finding the product of array elements with reduce() in JavaScript
- Consecutive elements sum array in JavaScript
- Reduce array in JavaScript
- Cumulative sum at each index in JavaScript
- Elements greater than the previous and next element in an Array in C++
- Mask array elements greater than or equal to a given value in Numpy
- Absolute sum of array elements - JavaScript
- Cumulative average of pair of elements in JavaScript

Advertisements