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

170
Vistas
JavaScript sort dates with a custom boolean value

I have an array of objects, these objects contains dates and one of them contains an

noDate: true

value. I would like to sort these dates, current I am able to sort them like this:

data.sort((a, b) => a.date - b.date)

But I need to sort them so the object with the noDate true value becomes the first one in the array. I tried this, but it does not work properly:

data.sort((a, b) => a.noDate === true ? -1 : a.date - b.date)
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You could take the boolean/undefined value and take the delta by converting the value to a negated boolean value first. Then sort by date.

const
    data = [
        { id: 0, noDate: true },
        { id: 1, date: new Date('2021-10-30') },
        { id: 2, date: new Date('2020-10-30') },
        { id: 3, noDate: true },
    ];

data.sort((a, b) => !a.noDate - !b.noDate || a.date - b.date);
console.log(data);

data.sort((a, b) => !b.noDate - !a.noDate || a.date - b.date);
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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