Home >Web Front-end >JS Tutorial >How Can I Sort an Array of Objects by Date in Descending Order in JavaScript?
Sorting Object Arrays by Date Property
Problem: You have an array of objects with a date property and want to sort it in descending order based on the closest date to the present.
Solution:
Using a Custom Comparator:
One approach is to use the built-in sort() method along with a custom comparator function. The comparator function takes two objects as arguments, a and b, and returns a negative, positive, or zero value if a should come before b, after b, or if they should remain in the same position, respectively.
For sorting by date, the comparator function would convert the date strings to JavaScript dates and subtract them:
array.sort(function(a, b) { return new Date(b.date) - new Date(a.date); });
Generic Solution:
A more generic solution is to define a custom sortBy() function that performs a Schwartzian transform on the array. This function can be used to sort by any property, not just the date.
(function() { if (!Array.prototype.sortBy) Array.prototype.sortBy = sb; function sb(f) { // ... implementation } })();
Using this custom function, you can sort by the date property as follows:
array.sortBy(function(o) { return o.date });
Handling Complex Date Comparisons:
If your date property is not directly comparable, you can extract a comparable value from it, such as a JavaScript Date object:
array.sortBy(function(o) { return new Date(o.date) });
Sorting by Multiple Criteria:
You can also use the sortBy() function to sort by multiple criteria. Simply return an array of values from the comparator function:
// Sort by date, then score (reversed), then name array.sortBy(function(o) { return [o.date, -o.score, o.name] });
The above is the detailed content of How Can I Sort an Array of Objects by Date in Descending Order in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!