
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Leaders array JavaScript
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]
- Related Articles
- How to find all leaders in an array in Java?
- 9 Thought Leaders Worth Following
- The Most Influential Leaders of Our Time
- How Can Leaders Improve Problem-Solving Abilities?
- The Benefits of Mindfulness for Business Leaders
- JavaScript Array Ranking - JavaScript
- Why film stars make bad leaders in India?
- Types of Mobile Wallets and Leaders in India
- 8 Lessons You Can Learn from Business Leaders
- The Best Qualities The Best Qualities of Community Leaders
- Importance of Selecting High-Potential Leaders in an Organization
- The Importance of Continuous Learning and Development for Leaders
- JavaScript Array reverse()
- JavaScript Array shift()
- JavaScript Array slice()

Advertisements