How can I obtain the max number of a JavaScript Array containing strings?
JavaScript
x
2
1
const array = ['a', 3, 4, 2] // should return 4
2
Here’s my answer but I got NaN
JavaScript
1
7
1
function maxNum(arr) {
2
for(let i=0; i<arr.length; i++){
3
return Math.max.apply(Math, arr);
4
}
5
}
6
maxNum(array) //NaN
7
Advertisement
Answer
You could use filter and typeof to check for number only.
JavaScript
1
6
1
const array = ['a', 3, 4, 2] // should return 4
2
3
function myArrayMax(x) {
4
return Math.max(x.filter(x => typeof x === 'number')); //result is 4
5
}
6
console.log(myArrayMax(array)) //4
Using Math.max.apply method
JavaScript
1
6
1
const array = ['a', 3, 4, 2] // should return 4
2
3
function myArrayMax(x) {
4
return Math.max.apply(null, x.filter(x => typeof x === 'number')); //result is 4
5
}
6
console.log(myArrayMax(array)) //4