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 ]

Updated on: 16-Sep-2020

92 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements