Find the Biggest Number in an Array with Undefined Elements in JavaScript



We are required to write a JavaScript function that takes in an array that contains some numbers, some strings and some falsy values.

Our function should return the biggest Number from the array.

For example −

If the input array is the following with some undefined values −

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

Then the output should be 65

Example

Following is the code −

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

This will produce the following output on console −

65
Updated on: 2020-10-01T10:57:35+05:30

199 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements