

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding the third maximum number within an array in JavaScript
We are required to write a JavaScript function that takes in an array of numbers as the first and the only argument.
The task of our function is to pick and return the third maximum number from the array. And if the array does not contain any third maximum number then we should simply return the maximum number from the array.
For example −
If the input array is −
const arr = [34, 67, 31, 87, 12, 30, 22];
Then the output should be −
const output = 34;
Example
The code for this will be −
const arr = [34, 67, 31, 87, 12, 30, 22]; const findThirdMax = (arr = []) => { const map = {}; let j = 0; for (let i = 0, l = arr.length; i < l; i++) { if(!map[arr[i]]){ map[arr[i]] = true; }else{ continue; }; arr[j++] = arr[i]; }; arr.length = j; let result = -Infinity; if (j < 3) { for (let i = 0; i < j; ++i) { result = Math.max(result, arr[i]); } return result; } else { arr.sort(function (prev, next) { if (next >= prev) return -1; return 1; }); return arr[j - 3] }; }; console.log(findThirdMax(arr));
Output
And the output in the console will be −
34
- Related Questions & Answers
- JavaScript Finding the third maximum number in an array
- Finding confusing number within an array in JavaScript
- Third smallest number in an array using JavaScript
- Finding unlike number in an array - JavaScript
- Third Maximum Number in C++
- Number of vowels within an array in JavaScript
- Finding the nth missing number from an array JavaScript
- Finding the maximum in a nested array - JavaScript
- Finding the largest 5 digit number within the input number using JavaScript
- Finding the first non-consecutive number in an array in JavaScript
- Finding the largest non-repeating number in an array in JavaScript
- Finding maximum number from two arrays in JavaScript
- Finding the sub array that has maximum sum JavaScript
- Finding the rotation of an array in JavaScript
- Finding the mid of an array in JavaScript
Advertisements