0

I have this simple issue that I can't figure out trying to find out the max from a string, yes it is a string, converting to a float. According to JS it can take an array... but everytime I try to find the max it is just printing the first value. In this case 13... not sure why? The expected result is 30.

Please help. Thanks!

function myFunction() {
 var str = "13, 24, 30, 4";//30
 var res = str.split(",");
 var max = Math.max(parseFloat(res));
 document.getElementById("demo").innerHTML = res+ " " + max;//test
 }
asked Feb 23, 2015 at 16:22
3
  • 4
    res is an array. parseFloat takes a string. Math.max does not take an array, but multiple arguments. Commented Feb 23, 2015 at 16:23
  • 1
    Take a look at Bergi's answer. Pay special attention to how he's using the "apply" on the Math.max function. Commented Feb 23, 2015 at 16:28
  • I will try to test this out. I have actually found a solution myself a couple of hours later. It does help to find some expert or experienced opinions. Thanks a bunch! Commented Feb 24, 2015 at 16:39

1 Answer 1

5

res is an array. parseFloat takes a string. Math.max does not take an array, but multiple arguments. Notice that you don't even need parseFloat, as Math.max casts its arguments to numbers anyway. So you have to use apply to get the array into Math.max:

var str = "13, 24, 30, 4";
var max = Math.max.apply(Math, str.split(", "));
document.getElementById("demo").innerHTML = "max("+res+") = "+max;
answered Feb 23, 2015 at 16:26

1 Comment

Oh sorry Bergi! Thanks! I didn't know that's how to do it in here such a noob.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.