Home > Article > Web Front-end > 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);
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:
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!