Greatest number in a dynamically typed array in JavaScript


We are required to write a JavaScript function that takes in an array that contains some numbers, some strings and some false values. Our function should return the biggest Number from the array.

For example: If the input array is −

const arr = [23, 'hello', undefined, null, 21, 65, NaN, 1, undefined, 'hii'];

Then the output should be 65.

Therefore, let’s write the code for this function −

Example

The code for this will be −

const arr = [23, 'hello', undefined, null, 21, 65, NaN, 1, undefined, 'hii'];
const pickBiggest = arr => {
   let max = -Infinity;
   for(let i = 0; i < arr.length; i++){
      if(!+arr[i]){
         continue;
      };
      max = Math.max(max, +arr[i]);
   };
   return max;
};
console.log(pickBiggest(arr));

Output

The output in the console will be −

65

Updated on: 24-Oct-2020

76 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements