Sorting Objects by Date Key Efficiently
An array of objects with multiple key-value pairs needs to be sorted based on the 'updated_at' key, which holds dates. The goal is to find the most efficient method for accomplishing this task.
One effective approach is to use the Array.sort() method. This function takes a comparison function as an argument, which determines the sorting order. Below is an example demonstrating the implementation:
var arr = [{</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">"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);
Inside the comparison function, each element's 'updated_at' values are converted into Date objects and compared. The sort order is established by returning -1 if keyA is earlier, 1 if keyA is later, or 0 if they are equal. This process ensures that the array is sorted in ascending order of dates.
The above is the detailed content of How to Efficiently Sort Objects by Date Key Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!