We can find this problem in our daily lives working with JavaScript, and of course we can use libraries that abstract this away for us. Nevertheless, it can be interesting to understand how to implement this feature and not rely on third party packages that might bring more complexity to your project.

Let's say you have an array of dates in a string format (e.g. 'yyyy-mm-dd') and you would like to sort it. With JavaScript, a good approach is to transform these dates in Date objects, and then use the Array method sort:

function fromStringToDate(date) {
 	// transforms string in array, splitting at the “-“
	const arrDate = date.split(“-“)
	const day = arrDate[2] ;
	// JavaScript represents the months starting at “0”
 	// but that's content for another post :)
 	const month = arrDate[1] - 1;
 	const year = arrDate[0];
    
    return new Date(year, month, day);
}

function compareDates(date1, date2) {
	if (date1 > date2) {
        return -1;
    } else if (date1 < date2) {
        return 1;
    } else {
        return 0;
    }
    // This code could be simplified to a one-liner:
    // return (date1 > date2) ? -1 : ((date1 < date2) ? 1 : 0)
}

const dates = [
	“2020-02-01”,
	“2020-01-05”,
	“2020-03-20”
];

dates
	.map(fromStringToDate)
	.sort(compareDates)

// [
//   Fri Mar 20 2020 00:00:00 GMT-0300 (-03),
//   Sat Feb 01 2020 00:00:00 GMT-0300 (-03),
//   Sun Jan 05 2020 00:00:00 GMT-0300 (-03)
// ]

If you want to invert the order, you just need to change the operator < to > and vice-versa.