Sort an Array of dates in ascending order using Custom Comparator | Comparator to sort the array of dates ; Condition to check the year ; Condition to check the month ; Condition to check the day ; Function that prints the dates in ascensding order ; Sort the dates using library sort function with custom Comparator ; Loop to print the dates ; Driver Code
function myCompare ( date1 , date2 ) { var day1 = date1 . substr ( 0 , 2 ) ; var month1 = date1 . substr ( 3 , 2 ) ; var year1 = date1 . substr ( 6 , 4 ) ; var day2 = date2 . substr ( 0 , 2 ) ; var month2 = date2 . substr ( 3 , 2 ) ; var year2 = date2 . substr ( 6 , 4 ) ; if ( year1 < year2 ) return - 1 ; if ( year1 > year2 ) return 1 ; if ( month1 < month2 ) return - 1 ; if ( month1 > month2 ) return 1 ; if ( day1 < day2 ) return - 1 ; if ( day1 > day2 ) return 1 ; } function printDatesAscending ( arr ) { var n = arr . length ; arr . sort ( myCompare ) ; for ( var i = 0 ; i < n ; i ++ ) document . write ( arr [ i ] + " " ) ; } var arr = [ ] ; arr . push ( " " ) ; arr . push ( " " ) ; arr . push ( " " ) ; arr . push ( " " ) ; arr . push ( " " ) ; printDatesAscending ( arr ) ;