过滤对象数组以返回具有最新日期属性的对象

时间:2016-02-04 13:22:15

标签: javascript angularjs date

如果我有这样的对象数组:

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的元素(对象)?

3 个答案:

答案 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;
&#13;
&#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);
   });