Return a subarray that contains all the element from the original array that are larger than all the 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 ]

Updated on: 19-Oct-2020

59 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements