Saturday, May 25, 2024
 Popular · Latest · Hot · Upcoming
152
rated 0 times [  155] [ 3]  / answers: 1 / hits: 20624  / 10 Years ago, tue, april 15, 2014, 12:00:00

How would I sort an array of dates in chronological order? For example I have:



var dates = [
'03/03/2014',
'01/03/2014',
'02/03/2014',
'04/03/2014'
];

sortDates = sortDate(dates);

sortDate(array){
// ?
returnt arraySort;
}


I'd like the resultant array to look like:



[
'01/03/2014',
'02/03/2014',
'03/03/2014',
'04/03/2014'
]

More From » arrays

 Answers
12

Assuming your date format is consistently DD/MM/YYYY:



dates.sort(function(a, b){
var aa = a.split('/').reverse().join(),
bb = b.split('/').reverse().join();
return aa < bb ? -1 : (aa > bb ? 1 : 0);
});


... otherwise you will have to compare Date objects if you require more flexibility.


[#71454] Sunday, April 13, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
samara

Total Points: 326
Total Questions: 106
Total Answers: 103

Location: Cook Islands
Member since Thu, May 21, 2020
4 Years ago
;