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
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.
Using Math.max with Array Filtering
The most straightforward approach is to filter valid numbers first, then use Math.max():
const arr = [23, 'hello', undefined, null, 21, 65, NaN, 1, undefined, 'hii'];
const pickBiggest = arr => {
const validNumbers = arr.filter(item => typeof item === 'number' && !isNaN(item));
return Math.max(...validNumbers);
};
console.log(pickBiggest(arr));
65
Using Manual Loop with Type Checking
For more control over the filtering process, we can manually iterate and check each element:
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++){
// Check if it's a valid number
if(typeof arr[i] === 'number' && !isNaN(arr[i])){
max = Math.max(max, arr[i]);
}
}
return max === -Infinity ? undefined : max;
};
console.log(pickBiggest(arr));
65
Using Reduce Method
The reduce() method provides a functional programming approach to find the maximum:
const arr = [23, 'hello', undefined, null, 21, 65, NaN, 1, undefined, 'hii'];
const pickBiggest = arr => {
return arr.reduce((max, current) => {
if(typeof current === 'number' && !isNaN(current)){
return Math.max(max, current);
}
return max;
}, -Infinity);
};
console.log(pickBiggest(arr));
65
Comparison of Methods
| Method | Readability | Performance | Handles Edge Cases |
|---|---|---|---|
| Filter + Math.max | High | Medium | Yes |
| Manual Loop | Medium | High | Yes |
| Reduce | High | Medium | Yes |
Key Points
-
typeof item === 'number'ensures we only consider numeric values -
!isNaN(item)excludesNaNvalues which are technically numbers -
-Infinityserves as the initial maximum value for comparison - All methods handle mixed data types effectively
Conclusion
When finding the greatest number in a mixed array, filter valid numbers first using type checking and NaN validation. The filter + Math.max approach offers the best balance of readability and functionality.
