How to Sort an Object Array by Date Property?
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...
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?
23 Answers
Must Read
Simplest Answer
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);
});