我有一个具有几个键值对的对象数组,我需要根据'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"
}
]
最有效的方法是什么?
使用下划线js或lodash,
var arrObj = [
{
"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"
}
];
arrObj = _.sortBy(arrObj,"updated_at");
_.sortBy()返回一个新数组
请参阅http://underscorejs.org/#sortBy和
lodash docs https://lodash.com/docs#sortBy
今天可以结合@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;
});