Reputation: 5161
I have following function:
var sortString = function (a, b) {
a = a.toLowerCase();
b = b.toLowerCase();
if (a < b) return 1;
if (a > b) return -1;
return 0;
}
and I have following two strings:
x = ["B1C3N_EUR_DFAK_ALL_3M_ALL","B1C3N_EUR_BPP_BCO_3M"];
When I run the above function on this array. I expect "B1C3N_EUR_BPP_BCO_3M" to be at index 0 whereas browser returns it in the reverse order. I have checked both on Chrome and IE. Why is it so??
Do I need to replace "-" with some other values. Is there any way I can do it without replacing.
Upvotes: 1
Views: 55
Reputation: 386700
You return the wrong value for smaller and greater value in the callback for Array#sort
.
if (a < b) return 1;
// ^ should be -1, because a is smaller than b
if (a > b) return -1;
// ^^ should be 1, because a is greater than b
For a more concise style, you could use String#localeCompare
, which test the given strings and returns a value in the wanted range.
Upvotes: 2