Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my very, very simple sort function return an unsorted list

If I do:

var my_list = ["g", "be", "d", "f", "hu", "i", "jc", "lu", "ma", "mi", "w"];
var sorted_list = my_list.sort(function(a,b) {
                        return a > b;
                       });
console.log(sorted_list);

I get:

["i", "g", "d", "f", "be", "hu", "jc", "lu", "ma", "mi", "w"]

(And if I try try it again I get a different unsorted result).

But when I do this:

var my_list = ["g", "be", "d", "f", "hu", "i", "jc", "lu", "ma", "mi", "w"];
var sorted_list = my_list.sort();
console.log(sorted_list);

I get the correct sorted result:

["be", "d", "f", "g", "hu", "i", "jc", "lu", "ma", "mi", "w"]

What is wrong with the function I'm providing to sort?

I can't use sort without a function because in my real code, I'm trying to sort objects. If this can't work, is there another way I can sort my objects by a certain attribute?

like image 552
user1136342 Avatar asked Feb 14 '23 09:02

user1136342


2 Answers

Comparison functions should return a value of -1, 0 or 1 depending on how the operands compare.

If you only perform an equality check (yielding 0 or 1) the sort result will be undefined, because the internal sort algorithm is inherently unstable.

This would be an equivalent of the standard sort:

if (a == b) {
    return 0;
} else if (a < b) {
    return -1;
} else { // a > b
    return 1;
}

The above is not extremely useful, but merely serves to illustrate which comparison elements should be present.

like image 139
Ja͢ck Avatar answered Feb 16 '23 02:02

Ja͢ck


Comparison function should return a number not a boolean. Alternatively you can use String.prototype.localeCompare method which is designed exactly for this purpose:

var sorted_list = my_list.sort(function(a, b) {
    return a.localeCompare(b);
});

The localeCompare() method returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.

like image 34
dfsq Avatar answered Feb 16 '23 02:02

dfsq