An element in an array of Numbers is a leader if it is greater than all the elements on its right side. We are required to write a JavaScript function that takes in an array of Numbers and returns a subarray of all the elements that are fulfil the criteria of being a leader element.
For example −
If the input array is: [23, 55, 2, 56, 3, 6, 7, 1] Then the output should be: [56, 7, 1]
Let's write the code for this function −
Example
const arr = [23, 55, 2, 56, 3, 6, 7, 1]; const leaderArray = arr => { const creds = arr.reduceRight((acc, val) => { let { max, res } = acc; if(val > max){ res.unshift(val); max = val; }; return { max, res }; }, { max: -Infinity, res: [] }) return creds.res; }; console.log(leaderArray(arr));
Output
The output in the console will be −
[56, 7, 1]