I have an array with a few objects, which is structured like this:
const combined =
{
id: "1",
desc: "Description One",
start: {
date: "2024-11-01",
}
},
{
id: "2",
desc: "Description Two",
start: {
dateTime: "2026-08-13T17:00:00+02:00",
}
},
{
id: "3",
desc: "Description Three",
start: {
date: "2023-03-28",
}
},
{
id: "4",
desc: "Description Four",
start: {
dateTime: "2026-08-13T15:00:00+02:00",
}
}
Based on different user input there either is a date date
or a date with timestamp dateTime
.
Now I want to sort the array based on the earliest date by using the object that exists date
or dateTime
.
In the given case the correct order should be:
{
id: "3",
desc: "Description Three",
start: {
date: "2023-03-28",
}
},
{
id: "1",
desc: "Description One",
start: {
date: "2024-11-01",
}
},
{
id: "4",
desc: "Description Four",
start: {
dateTime: "2026-08-13T15:00:00+02:00",
}
},
{
id: "2",
desc: "Description Two",
start: {
dateTime: "2026-08-13T17:00:00+02:00",
}
}
The earliest date is now [0]
and same day dates should be sorted by earliest time.
I tried to use Array.prototype.sort()
, but I guess I can’t compare the dates in that format.
2
Answers
The dates are string comparable without being converted. A localeCompare is enough and you can destruct the object to get at either date or dateTime
I STRONGLY assume same timezone, or this excercise is useless. What are the timezones supposed to be on dates without TZ?
Just properly convert date strings to local timezone dates and sort.
(as an example I’ve added
2026-08-13T16:00:00-01:00
so it would go before2026-08-13T15:00:00+02:00
).Regarding dates: since they don’t contain any timezone it’s assumeed they are in the local timezone: