从客户端的对象数组中获取最新日期的优雅方法是什么? [英] What is the elegant way to get the latest date from array of objects in client side?

查看:33
本文介绍了从客户端的对象数组中获取最新日期的优雅方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中使用 angularjs.

我从服务器获取对象数组.每个对象包含几个属性,其中之一是日期属性.

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

<预><代码>[{地址":25,警报类型":1,"区域": "北","MeasureDate": "2019-02-01T00:01:01.001Z",测量值":-1},{地址":26,警报类型":1,"区域": "西","MeasureDate": "2016-04-12T15:13:11.733Z",测量值":-1},{地址":25,警报类型":1,"区域": "北","MeasureDate": "2017-02-01T00:01:01.001Z",测量值":-1}...]

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

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

解决方案

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

ES6:

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

JS:

new Date(Math.max.apply(null, a.map(function(e) {返回新日期(e.MeasureDate);})));

其中 a 是对象数组.

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

通过将字符串日期映射到 JS 日期对象,您最终会使用类似 数组中日期的最小值/最大值?

--

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

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

如果性能是一个问题,您可能希望 reduce 数组以获得最大值,而不是使用 sortreverse.>

I use angularjs in project.

I get array of objects from the server. Each object contains few properties and one of them is date property.

Here is the Array (in json) that I get from server:

[
  {
    "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);
})));

where a is the array of objects.

What this does is map each of the objects in the array to a date created with the value of MeasureDate. This mapped array is then applied to the Math.max function to get the latest date and the result is converted to a date.

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

--

A less clean solution would be to simply map the objects to the value of MeasureDate and sort the array of strings. This only works because of the particular date format you are using.

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.

这篇关于从客户端的对象数组中获取最新日期的优雅方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆