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

Ell*_*one 1 javascript date angularjs

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

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
  }];
Run Code Online (Sandbox Code Playgroud)

我如何过滤它以便仅返回具有最新属性的元素(对象)date

Nin*_*olz 7

只需使用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>');
Run Code Online (Sandbox Code Playgroud)

  • 很好的答案...我在比较日期字符串和日期对象时遇到问题,并且能够使用修改后的版本使其正常工作:array.reduce((r,a)=&gt; new Date(r.date) &gt; new Date(a.date)?r:a); (2认同)

suv*_*roc 6

您应该使用排序功能:

没有空检查,你可以简单地使用

array.sort((a,b) => new Date(b.date).getTime() - new Date(a.date).getTime())[0];
Run Code Online (Sandbox Code Playgroud)