
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Find the Third Maximum Number in an Array using 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
Advertisements