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

193
Visualizações
Ordered Display of Array of Objects Based on Creation Date in ReactJS

I am trying to display the list of items that i am getting response from my get request response. So How do I sort on the basis of created date Mon, 18 Oct 2021 22:46:50 GMT is the date format I am displaying to my table. My code goes:

const display = todoList
.sort((a, b) => {
  return (
    new Date(a.createdAt).toUTCString() -
    new Date(b.createdAt).toUTCString()
  );
})
.map((item) => (
  <tr key={item.id}>
    <td>{item.title}</td>
    <td>{new Date(item.CreatedAt).toUTCString()}</td>

    <td>
      <button onClick={() => Update(item.id)} className="btn btn-success">
        Update
      </button>
    </td>
    <td>
      <button onClick={() => remove(item.id)} className="btn btn-Danger">
        Delete
      </button>
    </td>
  </tr>
));

response response picture

Json response

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

0

Your sort will not work like that. You can try something like this. I have no clue how your toDoList array looks, but here's a guess. And then you map.

toDoList.sort((a,b)=> {
  return new Date(b.createdAt) - new Date(a.createdAt);
});
about 4 years ago · Juan Pablo Isaza Relatório

0

Please take a look at the MDN Webdocs for sort(). Specifically, look at their example, it is returning 0, -1, or 1, and only these values. Your function, on the other hand, returns a UTC date (minus) another UTC date. What you need is not "string1 - string2", but "if string1 > string2 return 1, else", etc...

Change your sort to use -1 or 1, and string > comparisons instead of string - comparisons, like below, and it'll sort correctly...

todoList = [
 {'createdAt':'2000-01-01 12:00:00'},
 {'createdAt':'2000-01-01 10:00:00'},
];

todoList.sort((a, b) => {
  if(new Date(a.createdAt) > new Date(b.createdAt)) {
   return 1;
  }
  return -1;
});

console.log(todoList);

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