I know there have been a few questions similar to this but haven’t found a data structure like mine.
My array of objects
const dateAndTime = [
{
"createdAt": "20/02/2024, 16:13:51"
},
{
"createdAt": "20/02/2024, 16:15:23"
},
{
"createdAt": "18/02/2024, 14:27:31"
},
{
"createdAt": "18/02/2024, 15:41:06"
},
{
"createdAt": "21/03/2024, 22:09:35"
},
{
"createdAt": "07/03/2024, 17:24:19"
},
];
Here is the function I built to sort (Newest First)
dateAndTime.sort((a, b) => {
const dateA = new Date(a.createdAt);
const dateB = new Date(b.createdAt);
return dateB.getTime() - dateA.getTime();
});
console.log(dateAndTime);
OUTPUT
[
{
"createdAt": "20/02/2024, 16:13:51"
},
{
"createdAt": "20/02/2024, 16:15:23"
},
{
"createdAt": "18/02/2024, 14:27:31"
},
{
"createdAt": "18/02/2024, 15:41:06"
},
{
"createdAt": "21/03/2024, 22:09:35"
},
{
"createdAt": "07/03/2024, 17:24:19"
},
]
EXPECTED OUTPUT
[
{
"createdAt": "21/03/2024, 22:09:35"
},
{
"createdAt": "07/03/2024, 17:24:19"
},
{
"createdAt": "20/02/2024, 16:15:23"
},
{
"createdAt": "20/02/2024, 16:13:51"
},
{
"createdAt": "18/02/2024, 15:41:06"
},
{
"createdAt": "18/02/2024, 14:27:31"
},
]
As you can see, the output is pretty much the same, it doesnt seem to be sorting newest first. The expected output is newest first, so the 21st March 2024 10:09:35 PM should be the first object in the array, then it gets older from there.
Where am I going wrong here?
Many thanks in advance!
4
Answers
the default JavaScript Date constructor expects a date string in a format that can be recognized by the Date.parse() method, typically in the format of "YYYY-MM-DDTHH:mm:ss.sssZ". However, the dates in your createdAt property are in the format "DD/MM/YYYY, HH:mm:ss".
To properly parse the dates, you need to split the string and rearrange the elements to fit the expected format.
You will need to parse the date values into proper strings and sort by those:
To make your life easier, try using the MomentJS or Luxon library:
https://www.npmjs.com/package/luxon
And for your need, use the sort or diff function like so,
You don’t need to parse you date strings, just compare them character by character starting with year, for that first prepare an array of indices in which order to compare the characters.
If all of your dates in 2000x you can even skip the first 2 year chars.
This way it will be extremely fast since you don’t do any write operations: