You'll have to pass in a comparator function that converts the strings to numbers:
allsortedvalues = allsortedvalues.sort(function(a,b) {
return (+a) - (+b);
});
If there's a chance that some of your array entries aren't nicely-formatted numbers, then your comparator would have to get more complicated.
The construction (+a)
involves the unary +
operator, which doesn't do anything if a
is already a number. However if a
is not a number, the result of +a
will be either the value of a
when interpreted as a number, or else NaN
. A string is interpreted as a number in the obvious way, by being examined and parsed as a string representation of a number. A boolean value would be converted as false -> 0
and true -> 1
. The value null
becomes 0
, and undefined
is NaN
. Finally, an object reference is interpreted as a number via a call to its valueOf()
function, or else NaN
if that doesn't help.
It's equivalent to use the Number constructor, as in Number(a)
, if you like. It does exactly the same thing as +a
. I'm a lazy typist.