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

120
Vistas
Array of objects not sorted if I don't use map

Sorting this array of objects works if I map the objects first:

let data = [{
    "date": "2018-07-31T00:00:00Z"
}, {
    date: undefined
}, {
    "date": "2020-07-01T00:00:00Z"
}, {
    "date": "2019-08-24T11:16:26Z"
}, {
    "date": "2011-11-19T00:00:00Z"
}]

let compare = (a, b) => {
    if (a < b) return 1;
    if (a > b) return -1;
    return 0

}

// Note: Use map first
let result = data.map(x=>x.date);
console.log(result.sort(compare))

But if I sort this array without mapping the objects first, sort doesn't work:

let data = [{
    "date": "2018-07-31T00:00:00Z"
}, {
    date: undefined
}, {
    "date": "2020-07-01T00:00:00Z"
}, {
    "date": "2019-08-24T11:16:26Z"
}, {
    "date": "2011-11-19T00:00:00Z"
}]

// Similar compare function just adapted
let compare = (a, b) => {
    if (a.date < b.date) return 1;
    if (a.date > b.date) return -1;
    return 0

}

// Note: No map
let result = data;
console.log(result.sort(compare))

I can't see why this happens?

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

0

The problem is the object where the date is undefined. In the first example (with .map()), all the values are either strings or the one undefined. As per the specification of Array.prototype.sort():

"all undefined elements are sorted to the end of the array, with no call to compareFunction"

(MDN)

In the first example, the function is never called for the undefined value, so it is sorted last. In the second example, however, whenever you get a.date on the undefined value, you get undefined. Both if statements in the sort function then resolve to false since undefined can't be less than or greater than a string. Therefore, 0 is continually returned for the following elements. The undefined remains in place and breaks the rest of the sorting.

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