1

I'm trying to sort an array by date in React but it is not working. My dates are in this format: "2021-06-22 01:20:34" so "YYYY-MM-DD HH:MM:SS". I have this sorting function:

notifications.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))

but it does not work. I assume this is because the dates are in the wrong format. Do I need to change the format of the dates for the sorting function to work?

This is the array (called notifications):

[{username: "test", timestamp: "2021-06-22 01:20:34"},
{username: "test1", timestamp: "2021-02-27 01:34:22"},
{username: "test2", timestamp: "2021-06-22 01:13:29"},
{username: "test3", timestamp: "2021-03-07 02:27:30"},
{username: "test4", timestamp: "2021-03-07 02:24:11"},
{username: "test5", timestamp: "2021-06-22 01:11:38"},
{username: "test6", timestamp: "2021-06-22 01:14:46"},
{username: "test7", timestamp: "2021-02-28 17:15:05"}]

This is the code:

console.log(notifications)
var sorted_meetings = notifications.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))
console.log(sorted_meetings)

Sorted meetings is in the exact same order.

maximum360
  • 43
  • 4

0 Answers0