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

73
Vistas
Sorting with multiple conditions

I have an array of objects like so:

[
    { 
        required: false,
        sort: 1
    },
    { 
        required: true,
        sort: 2
    },
    { 
        required: false,
        sort: 3
    },
]

I want to sort it by required DESC, sort ASC. How do you do this?

The result I am looking for is:

[
    { 
        required: true,
        sort: 2
    },
    { 
        required: false,
        sort: 1
    },  
    { 
        required: false,
        sort: 3
    },
]

Currently tried with this, which doesnt work. It correctly puts required first, but then ignores sort for the required items:

arr.sort((a, b) => {
    if (a.required) return -1

    return a.sort - b.sort
})
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can subtract the second required (2) from the first (1) when comparing. If they are the same value, you can logical-OR the left (1) and right (2) sort values.

const data = [
  { required: false , sort: 1 },
  { required: true  , sort: 2 },
  { required: false , sort: 3 },
];

const sorted = data.sort((
  { required: r1, sort: s1 },
  { required: r2, sort: s2 }
) => r2 - r1 || s1 - s2);

console.log(sorted);
.as-console-wrapper { top: 0; max-height: 100% !important }

In JavaScript, subtracting booleans results in an integer value that is useful for sorting.

true  - true   //  0 (no change)
true  - false  // +1 (sink to bottom)
false - true   // -1 (float to top)
false - false  //  0 (no change)
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