Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to find the biggest number in an array around undefined elements? - 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
Solution Approach
We'll filter out non-numeric values and find the maximum among valid numbers. The key is to properly identify numeric values while handling edge cases like NaN, null, and undefined.
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
Output
This will produce the following output on console ?
65
How It Works
The solution uses the unary plus operator (+) to convert values to numbers. The condition !+arr[i] skips falsy values after numeric conversion, including 0, NaN, null, undefined, and empty strings.
Alternative Method: Using filter() and Math.max()
const arr2 = [23, 'hello', undefined, null, 21, 65, NaN, 1, undefined, 'hii'];
const findBiggest = arr => {
const numbers = arr.filter(item => typeof item === 'number' && !isNaN(item));
return numbers.length > 0 ? Math.max(...numbers) : -Infinity;
};
console.log(findBiggest(arr2));
65
Comparison
| Method | Handles NaN? | Readability | Performance |
|---|---|---|---|
| Loop with unary + | Yes (skips NaN) | Medium | Better for large arrays |
| filter() + Math.max() | Yes (explicit check) | High | Good for smaller arrays |
Conclusion
Both approaches effectively find the largest number while handling undefined and invalid values. The filter method is more readable, while the loop approach offers better performance for large datasets.
