如果我有这样的对象数组:
var array = [
{
"id": 5,
"date": "2016-01-15T16:18:44.258843Z",
"status": "NEW",
"created_at": "2016-01-29T13:30:39.315000Z",
"updated_at": "2016-01-29T13:30:39.315000Z",
"request": 4
},
{
"id": 6,
"date": "2016-01-19T16:18:44.258843Z",
"status": "STD",
"created_at": "2016-01-29T13:30:39.372000Z",
"updated_at": "2016-01-29T13:30:39.372000Z",
"request": 4
},
{
"id": 7,
"date": "2016-01-23T16:18:44.258843Z",
"status": "FOR",
"created_at": "2016-01-29T13:30:39.417000Z",
"updated_at": "2016-01-29T13:30:39.417000Z",
"request": 4
}];
如何过滤它以便仅返回具有最新属性date
的元素(对象)?
答案 0 :(得分:5)
只需使用Array#reduce并返回具有最新日期的对象(当您有ISO日期时,可以直接比较它):
var array = [{ "id": 5, "date": "2016-01-15T16:18:44.258843Z", "status": "NEW", "created_at": "2016-01-29T13:30:39.315000Z", "updated_at": "2016-01-29T13:30:39.315000Z", "request": 4 }, { "id": 6, "date": "2016-01-19T16:18:44.258843Z", "status": "STD", "created_at": "2016-01-29T13:30:39.372000Z", "updated_at": "2016-01-29T13:30:39.372000Z", "request": 4 }, { "id": 7, "date": "2016-01-23T16:18:44.258843Z", "status": "FOR", "created_at": "2016-01-29T13:30:39.417000Z", "updated_at": "2016-01-29T13:30:39.417000Z", "request": 4 }],
latest = array.reduce(function (r, a) {
return r.date > a.date ? r : a;
});
document.write('<pre>' + JSON.stringify(latest, 0, 4) + '</pre>');
&#13;
答案 1 :(得分:2)
您应该使用sort功能:
没有空检查你可以简单地使用
array.sort(function(a,b) {
return new Date(b.date).getTime() - new Date(a.date).getTime()
})[0];
答案 2 :(得分:2)
试试:
array.sort(function(a, b) {
return Date.parse(a.date) - Date.parse(b.date);
});