1

I have the following array of dates.

[ "1/22/20", "1/23/20", "1/24/20", "1/25/20", "1/26/20", "1/27/20", "1/28/20", "1/29/20", "1/30/20", "1/31/20", "2/1/20", "2/10/20", "2/11/20", "2/12/20", "2/13/20", "2/14/20", "2/15/20", "2/16/20", "2/17/20", "2/18/20", "2/19/20", "2/2/20", "2/20/20", "2/21/20", "2/22/20", "2/23/20", "2/24/20", "2/25/20", "2/26/20", "2/27/20", "2/28/20", "2/29/20", "2/3/20", "2/4/20", "2/5/20", "2/6/20", "2/7/20", "2/8/20", "2/9/20", "3/1/20", "3/2/20", "3/3/20" ]

The issue is that there is no leading 0s for days/months that are single digit.

I was wondering if there's some sort of built in function I can take advantage of in order to sort these dates in the correct order instead of using some loops and if statements.

Here is an example of the dates not being in order due to leading 0s

"1/31/20", "2/1/20", "2/10/20", "2/11/20", "2/12/20", "2/13/20",
  • Are they not already in the correct order? – fubar Mar 05 '20 at 05:10
  • 1
    Does this answer your question? [How to sort an array by a date property](https://stackoverflow.com/questions/10123953/how-to-sort-an-array-by-a-date-property) – Sudhir Ojha Mar 05 '20 at 05:14

1 Answers1

1

Write a custom sort function, which instantiates each date into a Date object before comparing them.

const dates = [ "2/6/20", "1/23/20", "1/25/20", "1/26/20", "2/16/20", "1/27/20", "1/28/20", "1/29/20", "1/30/20", "1/31/20", "2/1/20", "2/10/20", "2/11/20", "2/12/20", "2/13/20", "2/14/20", "2/15/20", "2/17/20", "2/18/20", "2/19/20", "2/2/20", "2/29/20", "2/20/20", "2/21/20", "1/22/20", "2/22/20", "2/23/20", "2/24/20", "2/25/20", "1/24/20", "2/26/20", "2/27/20", "2/28/20", "2/3/20", "2/4/20", "2/5/20", "2/7/20", "2/8/20", "2/9/20", "3/1/20", "3/2/20", "3/3/20" ];

dates.sort((a, b) => new Date(a) - new Date(b));

console.log(dates);
fubar
  • 14,318
  • 3
  • 29
  • 34