Why is my very simple sort function return an unsorted list

If I do this:

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 again, I get another 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 that I provide to sort?

I cannot use sorting without a function, because in my real code I am trying to sort objects. If this does not work, is there another way to sort the objects by a specific attribute?

+4
source share
2 answers

Comparison functions must return a value of -1, 0, or 1, depending on how the operands are compared.

( 0 1), undefined, .

:

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

, , .

+5

, . String.prototype.localeCompare, :

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

localeCompare() , , , .

+3

Source: https://habr.com/ru/post/1533660/


All Articles