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 −

 Live Demo

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

Updated on: 03-Mar-2021

122 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements