This seems to work, on an array of strings that look like numbers (they're numbers from a CSV file read in with csv-parse
, which seems to convert everything into strings):
var a = ['123.1', '1234.0', '97.43', '5678'];
Math.max.apply(Math, a);
Returns 5678
.
Does Math.max
convert strings to numbers automatically?
Or should I do a +
conversion myself first to be extra safe?
JavaScript Math class offers max () functions which return the largest the given numbers respectively. We can use them to find the maximum in a JS array: You have to use other method with max () to get max value element from array:- The recommended approach is to use Array.reduce () to find the maximum element in an array.
The Math.max () method returns the number with the highest value. Tip: Math.min () returns the number with the lowest value. Math.max () is an ES1 feature (JavaScript 1997). It is fully supported in all browsers: Optional. One or more numbers to compare A number, representing the highest number of the arguments. -Infinity if no arguments are given.
As the function name implies, Math.max () is handy when finding the max value within an array. There are several ways to use Math.max (). Depending on your use case, one approach might be more appropriate than others. Calling Math.max () without arguments returns -Infinity.
Because max() is a static method of Math, you always use it as Math.max(), rather than as a method of a Math object you created (Math is not a constructor).
Does Math.max convert strings to numbers automatically?
Quoting the ECMA Script 5.1 Specification for Math.max
,
Given zero or more arguments, calls
ToNumber
on each of the arguments and returns the largest of the resulting values.
So, internally all the values are tried to convert to a number before finding the max value and you don't have to explicitly convert the strings to numbers.
But watch out for the NaN
results if the string is not a valid number. For example, if the array had one invalid string like this
var a = ['123.1', '1234.0', '97.43', '5678', 'thefourtheye'];
console.log(Math.max.apply(Math, a));
// NaN
You'll get a NaN
if any of the strings aren't numbers, but otherwise it should work fine. I'd add the +
just to be safe.
Consider this situation:
<script>
var a=['123.1', '1234.0', '97.43', '5678','0 11111111'];
console.log(Math.max.apply(Math, a));
</script>
You need to cast elements from array to be extra safe..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With