Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

127
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda