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.