
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Return Subarray of Elements Larger Than All Elements on Their Right in JavaScript
We are required to write a JavaScript function that takes in an array of numbers and returns a subarray that contains all the element from the original array that are larger than all the elements on their right.
Therefore, let’s write the code for this function −
Example
The code for this will be −
const arr = [12, 45, 6, 4, 23, 23, 21, 1]; const largerThanRight = (arr = []) => { const creds = arr.reduceRight((acc, val) => { let { largest, res } = acc; if(val > largest){ res.push(val); largest = val; }; return { largest, res }; }, { largest: -Infinity, res: [] }); return creds.res; }; console.log(largerThanRight(arr));
Output
The output in the console will be −
[ 1, 21, 23, 45 ]
Advertisements