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
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
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);
//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)
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.