In JavaScript, an array of objects can be sorted by the date property using the sort function and a custom comparator.
The custom comparator function compares the dates of two objects and returns a value indicating how they should be ordered. Here's an example of a comparator function:
function dateComparator(a, b) { // Convert strings to dates and subtract them to get a date difference return new Date(b.date) - new Date(a.date); }
The sort function takes the comparator function as an argument and sorts the array accordingly. The result is an array of objects sorted by the date property in descending order from the most recent date.
array.sort(dateComparator);
Consider an array of objects with id and date properties:
const array = [{id: 1, date: "Mar 12 2012 10:00:00 AM"}, {id: 2, date: "Mar 8 2012 08:00:00 AM"}];
Sorting this array by date using the dateComparator function would result in:
[ {id: 2, date: "Mar 8 2012 08:00:00 AM"}, {id: 1, date: "Mar 12 2012 10:00:00 AM"} ]
The above is the detailed content of How to Sort an Array of JavaScript Objects by Date Property?. For more information, please follow other related articles on the PHP Chinese website!