'Is it safe to use JavaScript's Math.max on an array of strings?

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?



Solution 1:[1]

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

Solution 2:[2]

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.

Solution 3:[3]

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..

Solution 4:[4]

if you intend to check for the max element in an array of strings using Math.max() method. you can compare the length of reach element

question: var a = ['123.1', '1234.0', '97.43', '5678'];

const checkLength = Math.max.apply(null, a.map(element => element.length));

or using spread operator for shorter form

const checkLength = Math.max(...a.map(element => element.length));

then filter to get all the elements

a.filter(elem => elem.length === checkLength)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 thefourtheye
Solution 2 Alex McMillan
Solution 3 Rayon
Solution 4