
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
Find Element Larger Than All Elements on 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.
Example
Following is the code −
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
Following is the output in the console −
[ 1, 21, 23, 45 ]
Advertisements