I have a series of date strings that I'm pulling from an array. I'm trying to sort by year (desc), month (desc) and day (desc). I have figured out the year part, but I can't target the month and day.
const dates = [
{
date: "September 4, 2009"
},
{
date: "July 1, 2009"
},
{
date: "March 25, 2009"
},
{
date: "July 8, 2008"
},
{
date: "May 2, 2008"
},
{
date: "November 2, 2008"
},
{
date: "June 9, 2021"
},
{
date: "August 29, 2007"
},
{
date: "March 19, 2006"
},
{
date: "June 22, 2021"
},
{
date: "May 19, 2021"
}
];
dates.sort(function (a, b) {
if (a.date.substr(-4) > b.date.substr(-4)) {
return -1;
}
if (a.date.substr(-4) < b.date.substr(-4)) {
return 1;
}
return 0;
});
function datesTemplate(d) {
return `
<div class="card">
<h3>${d.date}</h3>
</div>
`;
}
document.getElementById("dateList").innerHTML = `${dates
.map(datesTemplate)
.join("")}`;
.card {
padding: 5px 10px;
border: 1px solid black;
margin: 1em;
}
<div class="container" id="dateList"></div>