小编典典

从客户端对象数组中获取最新日期的优雅方法是什么?

angularjs

我在项目中使用angularjs。

我从服务器获取对象数组。每个对象包含少量属性,其中之一是date属性。

这是我从服务器获得的数组(在json中):

[
  {
    "Address": 25,
    "AlertType": 1,
    "Area": "North",
    "MeasureDate": "2019-02-01T00:01:01.001Z",
    "MeasureValue": -1
  },
  {
    "Address": 26,
    "AlertType": 1,
    "Area": "West",
    "MeasureDate": "2016-04-12T15:13:11.733Z",
    "MeasureValue": -1
  },
  {
    "Address": 25,
    "AlertType": 1,
    "Area": "North",
    "MeasureDate": "2017-02-01T00:01:01.001Z",
    "MeasureValue": -1
  }
          .
          .
          .
]

我需要从数组中获取最新日期。

从对象数组获取最新日期的优雅方法是什么?


阅读 437

收藏
2020-07-04

共1个答案

小编典典

一种干净的方法是将每个日期转换为a Date()并采用最大值

new Date(Math.max.apply(null, a.map(function(e) {
  return new Date(e.MeasureDate);
})));

a对象数组在哪里。

这样做是将数组中的每个对象映射到使用值创建的日期MeasureDate。然后,将此映射数组应用于Math.max函数以获取最新日期,并将结果转换为日期。

通过将字符串日期映射到JS Date对象,您最终会使用诸如数组中日期的Min /Max之)类的解决方案吗?

-

不太干净的解决方案是简单地将对象映射到的值MeasureDate并对字符串数组进行排序。这仅适用于您所使用的特定日期格式。

a.map(function(e) { return e.MeasureDate; }).sort().reverse()[0]

如果需要考虑性能,则可能希望reduce使数组获得最大值而不是使用sortand reverse

2020-07-04