1

I have a array of JSON objects each having date as one of the fields.

var array = [{id: 1, date:'Mar 12 2012 10:00:00 AM'},{id: 2, date:'Mar 8 2012 08:00:00 AM'}]

I want to sort the objects in descending order on the basis of the time stamp. I have written a utility for it. i.e.

var sortedData= array .sort((function (a, b) { return new Date(b.date) - new Date(a.date) }));

but the above utility sorts on the basis of only date .i.e mar 12 and mar 8 in above case. It doesn't take into consideration the time factor which is 10.00 AM and 8.00 AM. How the sorting can be done using both the parameters, date as well as time.

rampuriyaaa
  • 4,288
  • 9
  • 31
  • 41
  • Works fine for me. Do note: `b-a` sorts in reverse (descending), so higher first. `a-b` sorts normally (ascending), so lower first. Did you mean to sort DESC? – Rudie May 26 '14 at 07:50
  • You can find some useful answers to this topic here: **[Sort Javascript Object Array By Date](http://stackoverflow.com/a/26759127/2247494)** – jherax Nov 05 '14 at 14:11

2 Answers2

2
var array = [{id: 1, date:'Mar 12, 2012 07:00:00 AM'},
             {id: 2, date:'Mar 12, 2012 08:00:00 AM'}];
var sortedData= array .sort((function (a, b) { 
                              return new Date(b.date) - new Date(a.date) 
                            }));
console.log(sortedData);

missing "," after year in your array

working fiddle (works perfectly even with identical values ​​that differ only between AM and PM)

http://jsfiddle.net/qR8cW/1/

faby
  • 6,838
  • 3
  • 24
  • 40
  • @Rudie Is better now? – faby May 26 '14 at 07:42
  • @Girish What are you saying? test and see how it works – faby May 26 '14 at 07:44
  • @Girish try with this values `var array = [{id: 1, date:'Mar 12, 2012 08:00:00 AM'},{id: 2, date:'Mar 12, 2012 08:00:00 PM'}];` and see the output – faby May 26 '14 at 07:46
  • I think so. `b - a` sorts reversed btw, so bigger first. – Rudie May 26 '14 at 07:46
  • @Girish in fact if you test `var array = [{id: 1, date:'Mar 12, 2012 08:00:00 AM'},{id: 2, date:'Mar 12, 2012 08:00:00 PM'}];` you'll see bigger ("PM") first. I think you are confused. – faby May 26 '14 at 07:48
0

You should be used timestamp for date comparison, and return comparison flag to sort function try this code

var array = [{id: 1, date:'Mar 12 2012 10:00:00 AM'},{id: 2, date:'Mar 8 2012 08:00:00 AM'}]
function SortByDate(a, b){
    var aD = new Date(a.date).getTime(), bD = new Date(b.date).getTime(); 
    return ((aD < bD) ? -1 : ((aD > bD) ? 1 : 0));
}
console.log(array.sort(SortByDate)); 

FIDDLE DEMO

Rudie
  • 46,504
  • 37
  • 126
  • 167
Girish
  • 11,254
  • 3
  • 32
  • 48