I've got the array of objects:
const data = [{
"id": "1",
"effectiveDate": "2023-01-21"
}, {
"id": "2",
"effectiveDate": "2023-02-22"
}, {
"id": "3",
"effectiveDate": "2022-05-04"
}, {
"id": "4",
"effectiveDate": "2022-05-05"
}, {
"id": "5",
"effectiveDate": "2021-01-21"
}, {
"id": "6",
"effectiveDate": "2021-02-22"
}];
What I'm after is the way to sort it in the way that the object with the most current date is on index 0 and the rest of the objects are ordered ascending from the oldest to future dates, like this:
[{
"id": "4",
"effectiveDate": "2022-05-05"
}, {
"id": "5",
"effectiveDate": "2021-01-21"
}, {
"id": "6",
"effectiveDate": "2021-02-22"
}, {
"id": "3",
"effectiveDate": "2022-05-04"
}, {
"id": "1",
"effectiveDate": "2023-01-21"
}, {
"id": "2",
"effectiveDate": "2023-02-22"
}]
The way I'm sorting it is:
const orderedDates = data.sort((a, b) => {
const dateCompareResult = new Date(a.effectiveDate) - new Date(b.effectiveDate);
return dateCompareResult;
});
which obviously gives me dates sorted ascending from the past dates to the future dates with the most current date somewhere in between. How can I move the most current date object to index 0?