Home >Web Front-end >JS Tutorial >How to Sort Objects by Date Value Using a Key?
Sorting Objects by Date Value Using a Key
To efficiently sort an array of objects by a single key with a date value, such as 'updated_at', you can utilize the built-in Array.sort method. Consider the following array:
[ { "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 by 'updated_at' in ascending order, you can use the following custom comparator function with the sort method:
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); if (keyA < keyB) return -1; if (keyA > keyB) return 1; return 0; }); console.log(arr);
In this comparator function, we convert the 'updated_at' values to Date objects (keyA and keyB) using the Date() constructor. We then compare these Date objects using comparison operators (<, >, and ==). If keyA is earlier than keyB, the function returns -1, indicating a need to swap the objects in the array. If keyA is later than keyB, the function returns 1, ensuring that keyA appears after keyB in the sorted array. The return value of 0 indicates that the objects are at the same position, and no swapping is required.
This sorting technique efficiently orders the objects by their 'updated_at' date values in ascending order. You can modify the comparison operators to achieve different sorting orders, such as descending order.
The above is the detailed content of How to Sort Objects by Date Value Using a Key?. For more information, please follow other related articles on the PHP Chinese website!