【问题标题】:Filter object array to return the object with the latest date property过滤对象数组以返回具有最新日期属性的对象
【发布时间】:2016-05-14 03:10:39
【问题描述】:

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

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

【问题讨论】:

    标签: javascript angularjs date


    【解决方案1】:

    你应该使用sort函数:

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

    array.sort((a,b) => new Date(b.date).getTime() - new Date(a.date).getTime())[0];
    

    【讨论】:

    • 谢谢,但是对于最新的日期,不应该是b - a 而不是a - b 吗?
    【解决方案2】:

    只需使用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>');

    【讨论】:

    • 优秀的答案...我在比较日期字符串和日期对象时遇到问题,我能够使用修改后的版本使其正常工作:array.reduce((r, a) = > 新日期(r.date) > 新日期(a.date) ? r : a);
    【解决方案3】:

    试试看:

    array.sort(function(a, b) {
            return Date.parse(a.date) - Date.parse(b.date);
       });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-27
      • 1970-01-01
      • 2018-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多