How to sort an object array by date property? – Dev

The best answers to the question “How to sort an object array by date property?” in the category Dev.


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?


@Phrogz answers are both great, but here is a great, more concise answer:

array.sort(function(a,b){return a.getTime() - b.getTime()});

Using the arrow function way


found here: Sort date in Javascript


Simplest Answer

  // Turn your strings into dates, and then subtract them
  // to get a value that is either negative, positive, or zero.
  return new Date( - new Date(;

More Generic Answer

  if (sort_o1_before_o2)    return -1;
  else if(sort_o1_after_o2) return  1;
  else                      return  0;

Or more tersely:

  return sort_o1_before_o2 ? -1 : sort_o1_after_o2 ? 1 : 0;

Generic, Powerful Answer

Define a custom non-enumerable sortBy function using a Schwartzian transform on all arrays :

  if (typeof Object.defineProperty === 'function'){
    try{Object.defineProperty(Array.prototype,'sortBy',{value:sb}); }catch(e){}
  if (!Array.prototype.sortBy) Array.prototype.sortBy = sb;

  function sb(f){
    for (var i=this.length;i;){
      var o = this[--i];
      this[i] = [].concat(,o,i),o);
      for (var i=0,len=a.length;i<len;++i){
        if (a[i]!=b[i]) return a[i]<b[i]?-1:1;
      return 0;
    for (var i=this.length;i;){
    return this;

Use it like so:

array.sortBy(function(o){ return });

If your date is not directly comparable, make a comparable date out of it, e.g.

array.sortBy(function(o){ return new Date( ) });

You can also use this to sort by multiple criteria if you return an array of values:

// Sort by date, then score (reversed), then name
array.sortBy(function(o){ return [, -o.score, ] };

See for more details.


Your data needs some corrections:

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

After correcting the data, you can use this piece of code:

function sortFunction(a,b){  
    var dateA = new Date(;
    var dateB = new Date(;
    return dateA > dateB ? 1 : -1;  

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


After correcting the JSON this should work for you now:

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

array.sort(function(a, b) {
    var c = new Date(;
    var d = new Date(;
    return c-d;