Home > Web Front-end > JS Tutorial > How Can I Sort an Array of Objects by Date in Descending Order in JavaScript?

How Can I Sort an Array of Objects by Date in Descending Order in JavaScript?

Susan Sarandon
Release: 2024-12-27 16:04:10
Original
737 people have browsed it

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);
});
Copy after login

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
  }
})();
Copy after login

Using this custom function, you can sort by the date property as follows:

array.sortBy(function(o) { return o.date });
Copy after login

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) });
Copy after login

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] });
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template