Home > Web Front-end > JS Tutorial > How to Sort Objects by Date Key Using Array.sort()?

How to Sort Objects by Date Key Using Array.sort()?

Susan Sarandon
Release: 2024-11-02 21:53:02
Original
325 people have browsed it

How to Sort Objects by Date Key Using Array.sort()?

Sorting Objects by Date Key Using Array.sort

Sorting an array of objects by a specific key is a common task in JavaScript. This can be particularly useful when dealing with timestamps like 'updated_at'.

To accomplish this, we can utilize the built-in Array.sort() method. This method takes a comparison function as its argument, which determines the order of the elements in the array.

For example, let's consider an array of objects with an 'updated_at' key:

[
    {
        "updated_at" : "2012-01-01T06:25:24Z",
        "foo" : "bar"
    },
    {
        "updated_at" : "2012-01-09T11:25:13Z",
        "foo" : "bar"
    },
    {
        "updated_at" : "2012-01-05T04:13:24Z",
        "foo" : "bar"
    }
]
Copy after login

To sort these objects based on the 'updated_at' key, we can use the following comparison function:

function compare(a, b) {
  var keyA = new Date(a.updated_at),
    keyB = new Date(b.updated_at);
  // Compare the 2 dates
  if (keyA < keyB) return -1;
  if (keyA > keyB) return 1;
  return 0;
}
Copy after login

This function compares the 'updated_at' values of two objects and returns a negative, positive, or zero value based on whether the first object is earlier, later, or the same time as the second object.

By passing this comparison function to the Array.sort() method, we can sort the array of objects in ascending order of 'updated_at':

arr.sort(compare);
Copy after login

The resulting sorted array will have the objects arranged from earliest to latest 'updated_at' value.

The above is the detailed content of How to Sort Objects by Date Key Using Array.sort()?. 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