Reputation: 35
How can I obtain the max number of a JavaScript Array containing strings?
const array = ['a', 3, 4, 2] // should return 4
Here's my answer but I got NaN
function maxNum(arr) {
for(let i=0; i<arr.length; i++){
return Math.max.apply(Math, arr);
}
}
maxNum(array) //NaN
Upvotes: 0
Views: 1334
Reputation: 3502
//as a note: `isNaN` have weird behaviour ..
MDN ref: link
const array = ['a', 3, 4, 2]
let result = Math.max(...(array.filter(el=>!isNaN(el))))
console.log(result)
Upvotes: 0
Reputation: 14570
You could use filter and typeof to check for number only.
const array = ['a', 3, 4, 2] // should return 4
function myArrayMax(x) {
return Math.max(...x.filter(x => typeof x === 'number')); //result is 4
}
console.log(myArrayMax(array)) //4
Using Math.max.apply method
const array = ['a', 3, 4, 2] // should return 4
function myArrayMax(x) {
return Math.max.apply(null, x.filter(x => typeof x === 'number')); //result is 4
}
console.log(myArrayMax(array)) //4
Upvotes: 1
Reputation: 20024
I think more efficient could be using array.prototype.reduce
:
var result = ['a', 3, 4, 2].reduce(
(a,b) => isNaN(a) ? b : (a>=b) ? a : b , 0) ;
console.log(result);
Because it only loops one time the array to get the highest number. The option of filtering and then Math.max
will require 2 loops.
Upvotes: 0
Reputation: 2587
If you wanna ignore strings and only take max from numbers. Math.max accepts numbers, not an array.
let array = ['a', 3, 4, 2] // should return 4
array = array.filter(a => !isNaN(Number(a)));
let max = Math.max(...array);
console.log(max);
Upvotes: 0