Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

localeCompare case-sensitive alphabetically issue

Tags:

javascript

I am trying to achieve aAbBcC here. I tried en-US expecting to get desired result. Expecting 'alpha' before 'Acuityads'.

var array = [{name:"Acuityads"},{name:"alpha"}];

console.log(array.sort(function(a,b){return a.name.localeCompare(b.name, 
'en-US-u-kf-lower'); }));


console.log(array.sort(function(a,b){return a.name.localeCompare(b.name, 
'en-US'); }));

"alpha".localeCompare("Acuityads", 'en-US') // output as 1
like image 390
Rashmi Avatar asked May 16 '26 20:05

Rashmi


1 Answers

As discussed in the comments, this looks like an inconsistency either in the spec or the vendor implementation.
Since an earlier question on the same topic didn't have any answers I'd be happy to go with, here's a manual implementation:

const input = ["aaaaa", "aaa", "aa", "aaaa", "aA", "Aa", "AA", "ab", "aB", "Ab", "AB"];

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;
}

console.log(input.sort(caseSensitiveCompare));
like image 169
Etheryte Avatar answered May 18 '26 08:05

Etheryte