How to find the biggest number in an array around undefined elements? - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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
raja
Published on 01-Oct-2020 10:57:35
Advertisements