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

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

问题描述

我在项目中使用angularjs。

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.

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

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?

推荐答案

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

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

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

其中 a 是对象数组。

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

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.

通过将字符串日期映射到JS Date对象,您最终使用的解决方案如数组中的最小/最大日期?

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 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]

如果表现是一个问题,你可能希望 reduce 数组得到最大值而不是使用 sort 反向

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天全站免登陆