# What is the best way to sort an object array by the date property?

## Problem

Let’s say I have a few things in an array:

``````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 order this array by date element, starting with the date closest to the current date and time and working my way down? Keep in mind that the array might include numerous objects, but I only chose two for the sake of simplicity.

Would I use a custom comparator and the sort function?

## Solution #1

``````array.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);
});
``````
``````array.sort(function(o1,o2){
if (sort_o1_before_o2)    return -1;
else if(sort_o1_after_o2) return  1;
else                      return  0;
});
``````

Or more tersely:

``````array.sort(function(o1,o2){
return sort_o1_before_o2 ? -1 : sort_o1_after_o2 ? 1 : 0;
});
``````

Create your own non-enumerable sort. Using a Schwartzian transform on all arrays, by function:

``````(function(){
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(f.call(o,o,i),o);
}
this.sort(function(a,b){
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;){
this[--i]=this[i][this[i].length-1];
}
return this;
}
})();
``````

Use it in the following way:

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

Make a comparable date out of your date if it isn’t immediately equivalent, e.g.

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

If you return an array of values, you can use this to sort by various criteria:

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

For further information, see http://phrogz.net/JS/Array.prototype.sortBy.js.

## Solution #2

@Phrogz Both replies are excellent, but here is a better, more simple one:

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

Using the arrow function is a good way to go.

``````array.sort((a,b)=>a.getTime()-b.getTime());
``````

found here: Sort date in Javascript

## Solution #3

This should now work for you after adjusting the JSON:

``````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(a.date);
var d = new Date(b.date);
return c-d;
});
``````

## Solution #4

You should make the following changes to your data:

``````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(a.date).getTime();
var dateB = new Date(b.date).getTime();
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"}];
array.sort(sortFunction);​
``````

## Solution #5

GitHub: Array sortBy – the finest implementation of the sortBy method that applies the Schwartzian transform.

But for the time being, we’ll use this Gist: sortBy-old.js. Let’s make a technique for sorting arrays and arranging objects based on some property.

``````var sortBy = (function () {
var toString = Object.prototype.toString,
// default parser function
parse = function (x) { return x; },
// gets the item to be sorted
getItem = function (x) {
var isObject = x != null && typeof x === "object";
var isProp = isObject && this.prop in x;
return this.parser(isProp ? x[this.prop] : x);
};

/**
* Sorts an array of elements.
*
* @param {Array} array: the collection to sort
* @param {Object} cfg: the configuration options
* @property {String}   cfg.prop: property name (if it is an Array of objects)
* @property {Boolean}  cfg.desc: determines whether the sort is descending
* @property {Function} cfg.parser: function to parse the items to expected type
* @return {Array}
*/
return function sortby (array, cfg) {
if (!(array instanceof Array && array.length)) return [];
if (toString.call(cfg) !== "[object Object]") cfg = {};
if (typeof cfg.parser !== "function") cfg.parser = parse;
cfg.desc = !!cfg.desc ? -1 : 1;
return array.sort(function (a, b) {
a = getItem.call(cfg, a);
b = getItem.call(cfg, b);
return cfg.desc * (a < b ? -1 : +(a > b));
});
};

}());
``````
``````var data = [
{date: "2011-11-14T17:25:45Z", quantity: 2, total: 200, tip: 0,   type: "cash"},
{date: "2011-11-14T16:28:54Z", quantity: 1, total: 300, tip: 200, type: "visa"},
{date: "2011-11-14T16:30:43Z", quantity: 2, total: 90,  tip: 0,   type: "tab"},
{date: "2011-11-14T17:22:59Z", quantity: 2, total: 90,  tip: 0,   type: "tab"},
{date: "2011-11-14T16:53:41Z", quantity: 2, total: 90,  tip: 0,   type: "tab"},
{date: "2011-11-14T16:48:46Z", quantity: 2, total: 90,  tip: 0,   type: "tab"},
{date: "2011-11-31T17:29:52Z", quantity: 1, total: 200, tip: 100, type: "visa"},
{date: "2011-11-01T16:17:54Z", quantity: 2, total: 190, tip: 100, type: "tab"},
{date: "2011-11-14T16:58:03Z", quantity: 2, total: 90,  tip: 0,   type: "tab"},
{date: "2011-11-14T16:20:19Z", quantity: 2, total: 190, tip: 100, type: "tab"},
{date: "2011-11-14T17:07:21Z", quantity: 2, total: 90,  tip: 0,   type: "tab"},
{date: "2011-11-14T16:54:06Z", quantity: 1, total: 100, tip: 0,   type: "cash"}
];
``````

Finally, we arrange the array into a string using the “date” attribute.

``````//sort the object by a property (ascending)
//sorting takes into account uppercase and lowercase
sortBy(data, { prop: "date" });
``````

Set the “parser” callback if you wish to ignore letter case:

``````//sort the object by a property (descending)
//sorting ignores uppercase and lowercase
sortBy(data, {
prop: "date",
desc: true,
parser: function (item) {
//ignore case sensitive
return item.toUpperCase();
}
});
``````

If you want to treat the “date” field as a Date type, use the following syntax:

``````//sort the object by a property (ascending)
//sorting parses each item to Date type
sortBy(data, {
prop: "date",
parser: function (item) {
return new Date(item);
}
});
``````

Play with the above example here: jsbin.com/lesebi