Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
142
rated 0 times [  144] [ 2]  / answers: 1 / hits: 53004  / 9 Years ago, fri, september 18, 2015, 12:00:00

I am trying to get the highest number from a simple array:



data = [4, 2, 6, 1, 3, 7, 5, 3];

alert(Math.max(data));


I have read that if even one of the values in the array can't be converted to number, it will return NaN, but in my case, I have double-checked with typeof to make sure they are all numbers, so what can be my problem?


More From » arrays

 Answers
31

The reason why your code doesn't work is because Math.max is expecting each parameter to be a valid number. This is indicated in the documentation as follows:



If at least one of arguments cannot be converted to a number, the result is NaN.



In your instance you are only providing 1 argument, and that 1 value is an array not a number (it doesn't go as far as checking what is in an array, it just stops at knowing it isn't a valid number).


One possible solution is to explicitly call the function by passing an array of arguments. Like so:


Math.max.apply(Math, data);

What this effectively does is the same as if you manually specified each argument without an array:


Math.max(4, 2, 6, 1, 3, 7, 5, 3);

And as you can see, each argument is now a valid number, so it will work as expected.


Spreading an array


You can also spread the array. This essentially treats the array as if each item is being passed as it's own argument.


Math.max(...data);

[#65013] Wednesday, September 16, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sidneyh

Total Points: 118
Total Questions: 108
Total Answers: 105

Location: Mali
Member since Fri, Jun 18, 2021
3 Years ago
sidneyh questions
Tue, Jun 7, 22, 00:00, 2 Years ago
Wed, Apr 13, 22, 00:00, 2 Years ago
Wed, Aug 12, 20, 00:00, 4 Years ago
Wed, Jun 3, 20, 00:00, 4 Years ago
Fri, Apr 24, 20, 00:00, 4 Years ago
;