- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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]
Advertisements