Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Finding the element larger than all elements on right - 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
