I have an array that is formatted like:
arr = [
{
'thing':'thing',
'thing2':'thing',
'date':'28/07/2014 14:16'
},
{
'thing':'thing',
'thing2':'thing',
'date':'27/07/2014 14:16'
}
]
I would like to sort it by date (most recent first, or rather, most recent at 0 index)
how can I do this?
UPDATE
something like
arr.sort(function(a,b){
return new Date(b.date) - new Date(a.date);
});
should in theory work, however, I have a problem with new date() returning 'invalid date' for some reason on some of the items in the array, for e.g:
arr.sort(function(a,b){
console.log(b.date)
console.log(new Date(b.date))
return new Date(b.date) - new Date(a.date);
});
and I get logged:
09/01/2014 14:23
Mon Sep 01 2014 14:23:00 GMT+0100 (GMT Daylight Time)
23/07/2014 09:04
Invalid Date
23/07/2014 09:04
Invalid Date
09/01/2014 14:23
Mon Sep 01 2014 14:23:00 GMT+0100 (GMT Daylight Time)
whats going on?
This should work, please check old IE browsers, i think it should work there as well http://jsfiddle.net/9t3Xq/
arr.sort(function(a, b) {
var valueA, valueB;
var dates1 = a.date.split(" ");
var dates2 = b.date.split(" ");
var dates1YMD = dates1[0].split("/");
var dates2YMD = dates2[0].split("/");
var dates1HIS = dates1[1].split(":");
var dates2HIS = dates2[1].split(":");
valueA = new Date(dates1YMD[2], dates1YMD[1], dates1YMD[0], dates1HIS[0], dates1HIS[1]);
valueB = new Date(dates2YMD[2], dates2YMD[1], dates2YMD[0], dates2HIS[0], dates2HIS[1]);
return valueB - valueA;
});
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments