Home > Web Front-end > JS Tutorial > body text

How to Sort an Array of Objects by a Single Date Key?

DDD
Release: 2024-11-04 02:41:02
Original
530 people have browsed it

How to Sort an Array of Objects by a Single Date Key?

Sorting an Array of Objects by a Single Date Key

To sort an array of objects by a single key that contains a date value, the most efficient approach is to utilize the Array.sort method. Here's how you can do it:

var arr = [{
    "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"
  }
];

arr.sort(function(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;
});

console.log(arr);
Copy after login

In this example, we have an array of objects named "arr" containing three objects, each with an "updated_at" key holding a date value.

The Array.sort method takes a compare function as an argument. In the compare function provided:

  1. We extract the "updated_at" values from each object as Date objects.
  2. We compare the two Date objects. If the first is earlier than the second, we return -1. If it's later, we return 1. If they are equal, we return 0.
  3. This compare function sorts the array in ascending order based on the "updated_at" values.

The sorted array is then logged to the console, displaying the objects in chronological order.

The above is the detailed content of How to Sort an Array of Objects by a Single Date Key?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template