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