0

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
4
  • what do you mean by the max in an array of strings? Or should it ignore when it is not a number and only get the max number? Commented Aug 14, 2020 at 3:53
  • const maxNum = arr => Math.max(...arr.filter(e => typeof e === 'number')); Commented Aug 14, 2020 at 3:55
  • @Dalorzo max number* sorry. I'm trying to find the max number in the array and I don't know how when there's a string in it Commented Aug 14, 2020 at 3:57
  • So if you did a search on how to filter only numbers in array you would find numerous results Commented Aug 14, 2020 at 3:58

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

What is this?
@charlietfl you can use this or null - MDN
My point is this is window if run in client side global space so really makes no sense to use it here
@charlietfl changed to it null if that makes more sense. Thanks :)
0

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);

2 Comments

Number(a) is not a good idea, not even like this. Take an input of [-1, 0].
My interpretation of the question was to ignore strings, which this doesn't, if the string can be converted to number. However, that's not completely clear from the question, so i guess it's up to OP to clarify.
0

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.

Comments

0
//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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.