Javascript: case sensitive string compare
Getting case sensitive string compare in Javascript isn’t as trivial as it may seem at first:
// Returns ["Action", "activity", "alpha"],
// although ["activity", "alpha", "Action"] is expected instead
["alpha", "Action", "activity"].sort((a, b) => {
return a.localeCompare(b, { sensitivity: 'case' });
});
The jury is still out on wheter this is an oversight in the spec or the common vendor implementations, in the meanwhile, a manual comparer does the trick:
function caseSensitiveCompare(a, b) {
// Sort character by character, return early if possible
for (let ii = 0; ii < Math.max(a.length, b.length); ii++) {
const aChar = a.charAt(ii);
const bChar = b.charAt(ii);
// If inputs match up to here, but lengths don't match, sort by length
if (!(aChar && bChar)) {
return a.length - b.length;
}
// If we meet a differing character, return early
const comp = aChar.localeCompare(bChar);
if (comp !== 0) {
return comp;
}
}
// If we found nothing to do, the strings are equal
return 0;
};
The above snippet covers full string sensitivity while still relying on localeCompare()
for the grunt work.
// Returns ["activity", "alpha", "Action"] as expected
["alpha", "Action", "activity"].sort(caseSensitiveCompare);