Home > Web Front-end > JS Tutorial > How to Sort an Array of JavaScript Objects by Date Property?

How to Sort an Array of JavaScript Objects by Date Property?

Linda Hamilton
Release: 2024-12-25 02:03:13
Original
605 people have browsed it

How to Sort an Array of JavaScript Objects by Date Property?

Sorting Object Arrays by Date Property

In JavaScript, an array of objects can be sorted by the date property using the sort function and a custom comparator.

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

Sort Function

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

Example

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

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

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!

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