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

191
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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