How would I sort an array of dates in chronological order? For example I have:
var dates = [
\'03/03/2014\',
Please do this the easy way.
Works for dates formatted as 'dd/mm/yy' or 'dd/mm/yyyy'.
var dates = [
'03/03/2014',
'01/03/2014',
'02/03/2014',
'04/03/2014'
];
dates.sort( function(c,d){
var rx = /(\d+)\/(\d+)\/(\d+)/;
var a = Number(c.replace(rx, '$3$1$20000'));
var b = Number(d.replace(rx, '$3$1$20000'));
return a > b ? -1 : a == b ? 0 : 1; // for newer on top
//return a < b ? -1 : a == b ? 0 : 1; // for older on top
});
Digigizmo answer works!
in case: dd/mm/yyyy hh:mm:ss you can use:
list.sort(function (a, b) {
var aa = a.substring(0, 10).split('/').reverse().join() + replaceAll(':', '', a.substring(11, 20)),
bb = b.substring(0, 10).split('/').reverse().join() + replaceAll(':', '', b.substring(11, 20));
return aa < bb ? -1 : (aa > bb ? 1 : 0);
});
and replaceAll function:
function replaceAll(find, replace, str) {
return str.replace(new RegExp(find, 'g'), replace);
}
Try this (feel free to ask for details) :
dates.sort(function (a, b) {
// '01/03/2014'.split('/')
// gives ["01", "03", "2014"]
a = a.split('/');
b = b.split('/');
return a[2] - b[2] || a[1] - b[1] || a[0] - b[0];
});
Translation of the last line :
return return
a[2] - b[2] years comparison if year A - year B is not 0
|| or
a[1] - b[1] months comparison if month A - month B is not 0
|| or
a[0] - b[0]; days comparison
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort.
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.
Just improving @leaf answer as split works on strings so you might get error if the type of 'a' and 'b' is object.
dates.sort(function (a, b) {
a = a.toString().split('/');
b = b.toString().split('/');
return a[2] - b[2] || a[1] - b[1] || a[0] - b[0];
});