Sort Javascript Object Array By Datejavascript


After correcting the JSON this should work.

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

var c = new Date(;
var d = new Date(;
return c-d;


Say I have an array of a few objects:

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

How can I sort this array by the date element in order from the date closest to the current date and time down? Keep in mind that the array may have many objects, but for the sake of simplicity I used 2.

Would I use the sort function and a custom comparator?


In my specific case, I wanted the dates arranged from the most recent to the oldest. It ended up that I had to reverse the simple function's logic as so:

array.sort(function(a, b) {
    a = new Date(a.dateModified);
    b = new Date(b.dateModified);
    return a>b ? -1 : a<b ? 1 : 0;

This sorts the dates from the most recent.

Sort array by date - javascript

Just write a sort function as given here. In your case the compare function will just be comparing two strings , which in the date format you have mentioned should work out of the box.

ie you can compare the two dates as strings.

how to sort json data by date

Put every object in an array and then call these function:

dates.sort(function(a,b){return a-b}); //asc
dates.sort(function(a,b){return b-a}); //desc

just change 'dates' to corresponding name of the array