I use angularjs in project.

我从服务器上获取对象array.

下面是我从服务器获得的Array(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
  }
          .
          .
          .
]

I need to get the latest date from the array.

What is the elegant way to get the latest date from array of objects?

推荐答案

A clean way to do it would be to convert each date to a Date() and take the max

ES6:

new Date(Math.max(...a.map(e => new Date(e.MeasureDate))));

JS:

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

其中a是对象array.

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

By mapping the string dates to JS Date objects, you end up using a solution like Min/Max of dates in an array?

--

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

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

If performance is a concern, you may want to reduce the array to get the maximum instead of using sort and reverse.

Jquery相关问答推荐

ASP.NET MVC - Ajax 将空值传递给控制器

获取 html 元素的 onclick 事件的 data-* 属性

缺少 .map 资源?

自动完成时触发的任何事件?

document.querySelector 一个元素中的多个数据属性

jQuery中的正则表达式字段验证

Chart.js 中饼图的点击事件

jQuery计算所有文本字段中的值的总和

你如何获得文本区域中的光标位置?

动画元素变换旋转

如何使用jQuery在弹出窗口中预览输入类型=文件中的选定图像?

动态创建并提交表单

使用 Jquery 更改页面标题

如何使用 jQuery 隐藏 div?

禁用 jquery Select 的下拉菜单

Backbone.js - 事件,知道点击了什么

jquery分别绑定双击和单击

使用 jQuery 获取选中复选框的值

在 javascript/浏览器中缓存 jquery ajax 响应

HTMLCollection、NodeLists 和对象数组之间的区别