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

128
Visualizações
How to customize sort an array

I'm trying to sort an array of objects in JS, but for some reason it doesnt work.

This is the code I'm running:

    let myArr = [{ "title": "AA" }, { "title": "ABC" }, { "title": "Ac" }, { "title": "adidas" }, { "title": "Ba" }, { "title": "BB" }]
    let sortList = myArr.sort(function (a, b) {
        const titleA = (a.title || '').substring(0, 1).toLowerCase();
        const titleB = (b.title || '').substring(0, 1).toLowerCase();
        return titleA > titleB ? 1 : -1;
    })
    console.log(sortList)

Output I am getting :

[
{
    "title": "adidas"
},
{
    "title": "Ac"
},
{
    "title": "ABC"
},
{
    "title": "AA"
},
{
    "title": "BB"
},
{
    "title": "Ba"
}

]

I actually wanted output as below:

  1. sort a after A

  2. sort B after A

  3. sort Ac after ABC

     [
         {
             "title": "AA"
         },
         {
             "title": "ABC"
         },
    
         {
             "title": "Ac"
         },
         {
             "title": "adidas"
         },
    
         {
             "title": "Ba"
         },
    
         {
             "title": "BB"
         }
     ]
    

Any idea what I did wrong? Thanks in advance for any help!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

.sort() and .localeCompare(). Note, in the OP, the input array is already sorted correctly so in this answer I have jumbled the order of the input array to demonstrate that the code functions correctly.

const data = [{ "title": "BB" }, { "title": "Ac" }, { "title": "adidas" }, { "title": "AA" }, { "title": "Ba" }, { "title": "ABC" }];

const output = data.sort((a, b) => a.title.localeCompare(b.title));

console.log(output);

about 4 years ago · Juan Pablo Isaza Relatório

0

You just need to sort it on lower case.

    let myArr = [{ "title": "AA" }, { "title": "ABC" }, { "title": "Ac" }, { "title": "adidas" }, { "title": "Ba" }, { "title": "BB" }]
    let sortList = myArr.sort(function (a, b) {
        return a.title.toLowerCase() > b.title.toLowerCase()
    })
    console.log(sortList)

about 4 years ago · Juan Pablo Isaza 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