Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

187
Visualizações
JavaScript: Sort a string that contains letters and numbers in a case-sensitive manner using Intl.Collator

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?

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda