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?
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.