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" } ]
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; }
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);
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!