Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't the sort function of javascript work well?

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!

like image 706
Christos Mitsis Avatar asked May 23 '11 06:05

Christos Mitsis


People also ask

Why does sort not work in JavaScript?

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.

Is sort stable in JavaScript?

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

Why array sort is not working?

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.

How sort function works in JavaScript?

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 .


3 Answers

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]);
}
like image 186
Tom Avatar answered Sep 28 '22 22:09

Tom


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});
like image 37
sje397 Avatar answered Sep 28 '22 22:09

sje397


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]);
}
like image 23
Tim Down Avatar answered Sep 28 '22 22:09

Tim Down