Reputation: 101
I am using the following code
function asc(a, b) {
return ($(b).text()) < ($(a).text());
}
When I pass a,d,c,e,b I get the correct values a,b,c,d,e
However when I pass a,d,C,e,b I get C,a,b,d,e
How can I make the code work when a different Case is used?
Upvotes: 0
Views: 38
Reputation: 1074595
If you're looking for a case-insensitive sort, the easiest way is to convert both sides to all-upper or all-lower case.
// Note: Not for Array#sort
function asc(a, b) {
return $(b).text().toLowerCase() < $(a).text().toLowerCase();
}
Note, thought, that I'm assuming you're not using this with Array#sort
, as it doesn't do what Array#sort
expects (return 0
, <0
, or >0
).
Side note: The ()
around $(b).text()
and $(a).text()
in your quoted code have no effect whatsoever, I've removed them above.
From your comment:
if I have to sequence the 'C' after 'c' in the example, how will i do it?
Ah, now that's different. This works for Array#sort
, you'll have to modify it to match however you're using asc
(I don't know what you expect to do in the case where strings match): Live Copy
// Note: Designed for Array#sort, may need modifying
function asc(a, b) {
var btext = $(b).text(),
atext = $(a).text(),
blc,
alc;
if (atext === btext) {
// Same
return 0;
}
alc = atext.toLowerCase();
blc = btext.toLowerCase();
if (alc === blc) {
// Case-insensitive match, compare case-sensitive and
// ensure uppercase comes after lowercase.
return atext < btext ? 1 : -1;
}
// Different even ignoring case
return alc < blc ? -1 : 1;
}
Upvotes: 5