0

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?

rpsep2
  • 3,061
  • 10
  • 39
  • 52
  • possible duplicate of [Sort Javascript Object Array By Date](http://stackoverflow.com/questions/10123953/sort-javascript-object-array-by-date) – Andy Jul 28 '14 at 13:22

2 Answers2

0

I love @Phrogz answer:

arr.sort(function(a,b){
  // Turn your strings into dates, and then subtract them
  // to get a value that is either negative, positive, or zero.
  return new Date(b.date) - new Date(a.date);
});
Community
  • 1
  • 1
Lior Elrom
  • 19,660
  • 16
  • 80
  • 92
0

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;
});
user2432612
  • 188
  • 1
  • 7