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?
Simplest Answer
More Generic Answer
Or more tersely:
Generic, Powerful Answer
Define a custom non-enumerable
sortByfunction using a Schwartzian transform on all arrays :Use it like so:
If your date is not directly comparable, make a comparable date out of it, e.g.
You can also use this to sort by multiple criteria if you return an array of values:
See http://phrogz.net/JS/Array.prototype.sortBy.js for more details.