This simple javascript
var x = new Array();
x[0] = 2.73;
x[1] = 11.17;
x[2] = 3.12
x.sort();
for(var i in x)
alert(x[i]);
produces the results:
11.17, 2.73, 3.12
instead of 2.73, 3.12, 11.17
.
Why is that and how can I fix it?
Thanks in advance!
This is because sort() needs a callback comparator, and when sort() is used without one, String() acts as the default callback. This is our callback function that will help sort the numbers in the correct and ascending order.
All major JavaScript engines now implement a stable Array#sort . It's just one less thing to worry about as a JavaScript developer. Nice! (Oh, and we did the same thing for TypedArray s: that sort is now stable as well.)
You sorting is failing because your comparison function does not meet the specifications for Array. sort : If compareFunction(a, b) is less than 0, sort a to an index lower than b, i.e. a comes first.
When the sort() function compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value. If the result is negative a is sorted before b . If the result is positive b is sorted before a .
It's sorting alphabetically, try passing your own sorting function:
var x = new Array();
x[0] = 2.73;
x[1] = 11.17;
x[2] = 3.12;
numberSort = function (a,b) {
return a - b;
};
x.sort(numberSort);
for(var i in x) {
alert(x[i]);
}
By default, Array.sort
will sort alphabetically (lexographically)...but you can supply your own function. Try:
x.sort(function(a, b) { return a > b ? 1 : -1});
Between them, the existing answers tell you everything, but none of them mention both of the problems in your code. Here's the full answer:
The sort isn't doing what you want because the default sort is lexical (i.e. the array elements are converted to strings and compared alphabetically). You can provide your own comparison function to sort()
:
x.sort(function(a, b) {
return a - b;
});
Secondly, for...in
is actually telling you nothing concrete about whether your array is sorted correctly, because the enumeration of for...in
is not defined (even though most but not all browsers do broadly what you'd expect). Use a for
loop instead (as indeed you generally should for arrays):
for (var i = 0, len = x.length; i < len; ++i) {
alert(x[i]);
}
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