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

256
Visualizações
How to sort notifications by dates in react?

I'm builing notifications component where I want to sort notification by dates and display them.

I tried but didn't work :

const result = notifications.notificationRows.sort((a, b) => b.time - a.time)

How can I do it over a following array ?

enter image description here

notificationRows: Array(25)
0:
notificationRow:
fee: "20 TEST"
id: "1.11.191431"
info: "[userlink=demo3], send 0.00021 TEST to ,[userlink=demo1]"
key: "1.11.191431"
time: "2022-05-17 16:54:21"
type: "transfer"
[[Prototype]]: Object
unread: false
[[Prototype]]: Object
1:
notificationRow:
fee: "20 TEST"
id: "1.11.191430"
info: "[userlink=demo3], send 0.012 TEST to ,[userlink=demo1]"
key: "1.11.191430"
time: "2022-05-17 14:52:39"
type: "transfer"
[[Prototype]]: Object
unread: false
[[Prototype]]: Object
2:
notificationRow:
fee: "20 TEST"
id: "1.11.191427"
info: "[userlink=demo3], send 0.0021 TEST to ,[userlink=demo1]"
key: "1.11.191427"
time: "2022-05-17 14:34:15"
type: "transfer"
[[Prototype]]: Object
unread: false

My expected result is :

enter image description here

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This does not works because you are comparing string instead of dates object. when you are trying to substract the two date in your sort function the result will always be NaN.

"2022-02-01 12:00:00" - "2022-02-02 12:00:00" // NaN

You can use the Date object to compare and sort your object.

This will transform your string into Date object that can be compared as you did.

new Date("2022-02-01 12:00:00") - new Date("2022-02-02 12:00:00") // -86400000 meaning the second date is after the first one

const notifications = {
  notificationRows: [{time: '2022-02-01 12:00:00'}, {time: '2022-01-01 12:00:00'}, {time: '2022-03-01 12:00:00'}]
}

const oldResult = notifications.notificationRows.sort((a, b) => b.time - a.time)
console.log("Your result", oldResult)

const result = notifications.notificationRows.sort((a, b) => new Date(b.time) - new Date(a.time))
console.log("New result", result)

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