我有一个包含多个键值对的对象数组,我需要根据 'updated_at' 对它们进行排序:
[
{
"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"
}
]
最有效的方法是什么?
最佳答案
您可以使用 Array.sort
.
这是一个例子:
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);
关于javascript - 通过具有日期值的单个键对对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8837454/