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

492
Visualizações
How do you sort letters in JavaScript, with capital and lowercase letters combined?

I'm working on a JavaScript (jQuery's OK too if this needs it, but I doubt it will) function to alphabetize a string of letters. Let's say the string that I want to sort is: "ACBacb".

My code as of now is this:

var string='ACBacb';
alert(string.split('').sort().join(''));

This returns ABCabc. I can see why that happens, but that is not the format that I am looking for. Is there a way that I can sort it by putting the same letters next to each other, capital letter first? So when I put in ACBacb, I get AaBbCc?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Array.sort can have a sort function as optional argument.

What about sorting the string first (ACBacbA becomes AABCabc), and then sorting it case-insensitive:

function case_insensitive_comp(strA, strB) {
    return strA.toLowerCase().localeCompare(strB.toLowerCase());
}

var str = 'ACBacbA';
// split the string in chunks
str = str.split("");
// sorting
str = str.sort();
str = str.sort( case_insensitive_comp )
// concatenate the chunks in one string
str = str.join("");

alert(str);

As per Felix suggestion, the first sort function can be omitted and merged in the second one. First, do a case-insensitive comparison between both characters. If they are equal, check their case-sensitive equivalents. Return -1 or 1 for a difference and zero for equality.

function compare(strA, strB) {
   var icmp = strA.toLowerCase().localeCompare(strB.toLowerCase());
   if (icmp != 0) {
       // spotted a difference when considering the locale
       return icmp;
   }
   // no difference found when considering locale, let's see whether
   // capitalization matters
   if (strA > strB) {
       return 1;
   } else if (strA < strB) {
       return -1;
   } else {
       // the characters are equal.
       return 0;
   }
}
var str = 'ACBacbA';
str = str.split('');
str = str.sort( compare );
str = str.join('');
over 4 years ago · Santiago Trujillo Relatório

0

You can pass a custom comparison function to Array.sort()


The already given answers are right so far that you have to use a custom comparison function. However you have to add an extra step to sort capital letters before lower case once:

function cmp(x,y) {
    if(x.toLowerCase() !== y.toLowerCase()) {
        x = x.toLowerCase();
        y = y.toLowerCase();
    }
    return x > y ? 1 : (x < y ? -1 : 0);
    // or return x.localeCompare(y);
}

If the letters are the same, the originals have to be compared, not the lower case versions. The upper case letter is always "larger" than the lower case version.

DEMO (based on @Matt Ball's version)

over 4 years ago · Santiago Trujillo Relatório

0

a working example http://jsfiddle.net/uGwZ3/

var string='ACBacb';
alert(string.split('').sort(caseInsensitiveSort).join(''));

function caseInsensitiveSort(a, b)
{
   var ret = 0;
   a = a.toLowerCase();b = b.toLowerCase();
   if(a > b)
      ret = 1;
   if(a < b)
      ret = -1;
   return ret;
}
over 4 years ago · Santiago Trujillo Relatório
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