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

132
Vistas
JavaScript sort array item after specific array id

I am sorting an array of object using the date values inside each object. I now have an edge case, if thenoDate property is set to true, that object shall be sorted after the object with the id 2.

An object looks something like this:

{
    id: 1 // just simple ids 1...99
    date: ...
    noDate: true // true or false
}

Currently its sorted like this, but that does not provide the logic I need.

data.sort((a, b) => (!a.noDate - !b.noDate) || new Date(a.date) - new Date(b.date))
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You could sort first to get all noDate: true at top of the array and then map a new array to get all top items after id: 2 object. This approach needs a finally

let
    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 },
        { id: 4, date: new Date('2021-09-30') },
        { id: 5, date: new Date('2020-09-15') },
        { id: 6, noDate: true }
    ];

data = data
    .sort((a, b) => !a.noDate - !b.noDate || a.date - b.date)
    .flatMap((a => o => {
        if (o.noDate) { a.push(o); return []; }
        if (o.id === 2) return [o, a];
        return o;
    })([]))
    .flat();

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

about 4 years ago · Juan Pablo Isaza Denunciar

0

simply

list.sort((a, b) => a.noDate ? -1 : new Date(a.date) - new Date(b.date))

Or if you want to sort by two field first sortNumber and then sorting by date

list.sort((a, b) => a.sortNumber == b.sortNumber ? new Date(a.date) - new Date(b.date): a.sortNumber - b.sortNumber)
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