JavaScript: Sort a string that contains letters and numbers in a case-sensitive manner using Intl.Collator

369 views Asked by At

With the requirement that I need to use the Intl.Collator (English language only) to sort strings that contains both letters and numbers (anywhere in the string). I need to have them sorted such that:

  1. Capital letters come before lower-case letters when they're the same (eg. A > a, a > b, a > B, A > B, A > b)
  2. Numbers in the string are sorted numerically (eg. 1 > 2, 1 > 10, 2 > 10)
  3. Numbers sort before letters (numbers > letters) when at the same position.

I am using this:

return new Intl.Collator(locale, { caseFirst: 'upper', numeric: true, sensitivity: 'variant' })
  .compare(stringA, stringB);

You can see an explanation of the Collator options object here: https://reference.codeproject.com/javascript/reference/global_objects/collator

This works fine when the numbers are at the beginning of the string:

'9elliot' > '12morgan',
'54mary' > '54Ralph',
'23John' > '23john'

But I have run across a case where sorting fails and I cannot figure out why:

console.log(['f1oobar', 'F2oobar'].sort(
  new Intl.Collator('en', { caseFirst: 'upper', numeric: true, sensitivity: 'variant'}).compare
));

// Prints ["f1oobar", "F2oobar"]

I need it to sort as ["F2oobar", "f1oobar"] because Capital "F" should come before lower-case "f".

I have tried all variants of caseFirst, numeric and sensitivity with no change in the result. I've even removed numeric and sensitivity with no change.

Who can explain and/or solve this?

0

There are 0 answers