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

76
Vistas
Sorting array of objects using localeCompare with possible false for value

I'm making a sorting function where sort by value will be dynamic and some values of properties in objects in the array can be false.

I Would like to use localeCompare due to possible special characters etc.

As seen in the example it breaks if a false value is in the middle of the array. I did try to implement optional changing but it does not work at all then:

return a.sortValue?.[1].localeCompare(b.sortValue?.[1])

The expected results Is:

for user_id: 4 1 2 3

and partner_id: 4 1 3 2

Sort value is always (when not false) in 1 index of the array. And would like false at the end, I still need it in the list...

Is this possible without making some custom sorting function?

let arr = [{
    id: 1,
    user_id: ["ignoreThis", 'B'],
    partner_id: ["ignoreThis", 'B']
  },
  {
    id: 2,
    user_id: ["ignoreThis", 'D'],
    partner_id: false
  },
  {
    id: 3,
    user_id: false,
    partner_id: ["ignoreThis", 'D']
  },
   {
    id: 4,
    user_id: ["ignoreThis", 'A'],
    partner_id: ["ignoreThis", 'A']
  }
]

const sortBy = sortValue => {
  arr.sort(function(a, b) {
    return a[sortValue][1].localeCompare(b[sortValue][1])
  })
}

sortBy('user_id')
arr.forEach(i => console.log(i.id))
sortBy('partner_id')
arr.forEach(i => console.log(i.id))
.as-console-wrapper {
  min-height: 100% !important;
}

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You could check the value first and the sort by the wanted value. This approach needs a default empty string for using localeCompare.

const
    array = [{ id: 1, user_id: ["ignoreThis", 'B'], partner_id: ["ignoreThis", 'B'] }, { id: 2, user_id: ["ignoreThis", 'D'], partner_id: false }, { id: 3, user_id: false, partner_id: ["ignoreThis", 'D'] }, { id: 4, user_id: ["ignoreThis", 'A'], partner_id: ["ignoreThis", 'A'] }] 
    sortBy = key => array.sort((a, b) =>
        !a[key] - !b[key] ||
        (a[key]?.[1] || '').localeCompare(b[key]?.[1])
    );

sortBy('user_id');
console.log(...array.map(({ id }) => id));
sortBy('partner_id');
console.log(...array.map(({ id }) => id));

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