3

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

9
  • you can specify also the sensitivity as option, please check the official doc on localecompare method
    – quirimmo
    Jan 22, 2021 at 9:50
  • @quirimmo I did tried that also { sensitivity: 'base'/'case'} but didn't worked. variant is by default
    – Rashmi
    Jan 22, 2021 at 9:52
  • also the locale can be used to specify it try as locale 'en-US-u-kf-lower'
    – quirimmo
    Jan 22, 2021 at 9:54
  • yes, I have added that one in description. Not working for me.
    – Rashmi
    Jan 22, 2021 at 9:56
  • 1
    @quirimmo it's indeed weird - comparing "A" and "a" (one character only) works, the lowercase character is sorted first. However, if you have more characters, it bases the comparison on the rest, e.g., "ac" comes after "Ab". Not sure why that behaviour - the way I read the documentation suggests it should stop if two characters are considered different but it seems to not do that.
    – VLAZ
    Jan 22, 2021 at 10:04

1 Answer 1

1

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

2
  • 1
    I've found the spec but I can't locate what behaviour is expected for caseFirst. I've been skimming it, though. I'm actually interested in why this is happening, so I'll try to read it more in depth.
    – VLAZ
    Jan 22, 2021 at 10:34
  • 1
    @Etheryte your manual implementation worked for me. Thanks a lot.
    – Rashmi
    Jan 22, 2021 at 11:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.