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

147
Vistas
Array sort with primary and secondary value

Is there a way to sort an array of objects using a primary and secondary value? What i mean is an array like this:

[
    { primary: 0, secondary: 'a' },
    { primary: 1, secondary: 'a' },
    { primary: 1, secondary: 'b' },
    { primary: 0, secondary: 'b' }
]

will be sorted using the primary value, so the first two objects with the primary value of 0 come first then the values of 1 come second, and then it will be again sorted by the secondary value and it will result in the array becoming

[
    { primary: 0, secondary: 'a' },
    { primary: 0, secondary: 'b' },
    { primary: 1, secondary: 'a' },
    { primary: 1, secondary: 'b' }
]

im havent really touched the Array.sort() before so im trying to find out how to do this, any help will be appreciated!

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

0

You can use Array#sort.

Comparison would be by primary first (numeric), or by secondary if equal (string using String#localeCompare)

const arr = [ { primary: 0, secondary: 'a' }, { primary: 1, secondary: 'a' }, { primary: 1, secondary: 'b' }, { primary: 0, secondary: 'b' } ];

const res = arr.sort((a, b) => 
  a.primary - b.primary || a.secondary.localeCompare(b.secondary)
);

console.log(res);

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