Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

121
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda