I am creating an array of objects, which looks like
let obj = {
date: String,
time: String,
text: String,
}
The date format is "MM-DD-YYYY" and format of time "HH:MM:SS"
I am getting this from an API and can’t change the format, I need to sort the array in increasing order of date and time, that is for the same date, increasing order of time. I have tried using JS Date and Moment, but was not able to do it.
Sorting only by date works using Date(a.date) - Date(b.date)
, but if I try to include the time as well, it does not, not even
(Date(a.date) - Date(b.date)) || (a.time.localeCompare(b.time))
How can I do this in JavaScript (NodeJS)?
3
Answers
I was able to solve this by the following sort function:
Cheers to ChatGPT!
You can convert the date and time strings to JavaScript Date objects and then use the sort() method:
With the following sorting logic, you can has the date and time together so that you do not need to re-parse each item every time it is compared to another.