我有一个具有几个键值对的对象数组,我需要根据'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"
}
]
最有效的方法是什么?
为了完整起见,这里有一个sortBy的简短泛型实现:
function sortBy(list, keyFunc) {
return list.sort((a,b) => keyFunc(a) - keyFunc(b));
}
sortBy([{"key": 2}, {"key": 1}], o => o["key"])
注意,这里使用了就地排序的数组排序方法。
对于副本,您可以使用arr.concat()或arr.slice(0)或类似的方法来创建副本。
今天可以结合@knowbody (https://stackoverflow.com/a/42418963/6778546)和@Rocket Hazmat (https://stackoverflow.com/a/8837511/6778546)的回答来提供ES2015的支持和正确的日期处理:
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((a, b) => {
const dateA = new Date(a.updated_at);
const dateB = new Date(b.updated_at);
return dateA - dateB;
});