1

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>
Millhorn
  • 2,953
  • 7
  • 39
  • 77

2 Answers2

3

this will parse the date and the compare function parses the dates and sorts them in descending order

dates.sort((a,b ) => new Date(b.date) - new Date(a.date))
Shahriar Shojib
  • 867
  • 8
  • 16
  • 1
    Huzzah! Much less complicated than a substring. – Millhorn Jun 25 '21 at 20:00
  • Seriously genius answer! Short code and works perfectly. Really cool. You played it like CodeGolf (https://codegolf.stackexchange.com/) – raddevus Jun 25 '21 at 20:27
  • See [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) The date string should be parsed manually (a library can help). – RobG Jun 26 '21 at 08:34
2

Use Date.parse() to turn the date to a timestamp, then sort by that.

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"
  }
];

console.log(dates.sort((a, b) => Date.parse(a.date) - Date.parse(b.date)));

If you are in control of the data source, it would be better to use a standard date format such as iso8601: 2009-08-04. iso8601 has the additional benefit (aside from standardization) that it is sortable as a string.

Charlie Bamford
  • 1,268
  • 5
  • 18