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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36577205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:15:09  来源:igfitidea点击:

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

javascriptjqueryangularjs

提问by Michael

I use angularjs in project.

我在项目中使用 angularjs。

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:

这是我从服务器获取的数组(在 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?

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

回答by arcyqwerty

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

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

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

where ais the array of objects.

a对象数组在哪里。

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.maxfunction to get the latest date and the result is converted to a date.

这样做是将数组中的每个对象映射到使用 值创建的日期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?

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

--

——

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

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

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

If performance is a concern, you may want to reducethe array to get the maximum instead of using sortand reverse.

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

回答by Travis Heeter

If you want to get the whole Object, not just the date...

如果你想获得整个对象,而不仅仅是日期......

If OP's array of Objects was assigned to athis is how you get the Object with the most recent date:

如果将 OP 的对象数组分配给a这就是获得具有最新日期的对象的方式:

var mostRecentDate = new Date(Math.max.apply(null, a.map( e => {
   return new Date(e.MeasureDate);
})));
var mostRecentObject = a.filter( e => { 
    var d = new Date( e.MeasureDate ); 
    return d.getTime() == mostRecentDate.getTime();
})[0];
  1. a.mapgets the dates from the array of objects.
  2. new Dateis applied to each date, making DateObjects
  3. Math.max.applyfinds the most recent
  4. We have found the most recent Date, now we need the object.
  5. a.filterloops through the original aarray.
  6. We need some way to compare dates, so we use .getTime(), which returns the number of milliseconds since 01/01/1970. This will account for time - if it's defined - as well as date.
  7. When the correct date is found, trueis returned, and .filtergives us just that object.
  1. a.map从对象数组中获取日期。
  2. new Date应用于每个日期,使日期对象
  3. Math.max.apply找到最近的
  4. 我们已经找到了最近的日期,现在我们需要这个对象。
  5. a.filter循环遍历原始a数组。
  6. 我们需要某种方法来比较日期,因此我们使用.getTime(),它返回自 1970 年 1 月 1 日以来的毫秒数。这将考虑时间 - 如果它已定义 - 以及日期。
  7. 当找到正确的日期时,true返回,并只.filter给我们那个对象。

Note: This solution is an extension of @archyqwerty's answer above. Their solution gave only the most recent date from an array of objects, this solution gives you the whole Object that the date was a member of.

注意:此解决方案是上述@archyqwerty 答案的扩展。他们的解决方案只给出了一组对象中的最新日期,这个解决方案为您提供了该日期所属的整个对象。

回答by Yorkshireman

Further to @Travis Heeter's answer, this returns the object that contains the latest date:

继@Travis Heeter 的回答之后,这将返回包含最新日期的对象:

array.reduce((a, b) => (a.MeasureDate > b.MeasureDate ? a : b));

array.reduce((a, b) => (a.MeasureDate > b.MeasureDate ? a : b));

A more robust solution perhaps might be convert the strings into Dateobjects every time. Could be noticeably slower if dealing with (very) large arrays:

更强大的解决方案可能是Date每次都将字符串转换为对象。如果处理(非常)大型数组,速度可能会明显变慢:

array.reduce((a, b) => {
  return new Date(a.MeasureDate) > new Date(b.MeasureDate) ? a : b;
})

回答by Larry Popiel

Modification to Anton Harald's answer: The array I have uses ModDate instead of MeasureDate. I am choosing the most recent date. This works.

对 Anton Harald 回答的修改:我拥有的数组使用 ModDate 而不是 MeasureDate。我正在选择最近的日期。这有效。

  getLatestDate(xs) {
   if (xs.length) {
   return xs.reduce((m,v,i) => (v.ModDate > m.ModDate) && i ? v : m).ModDate;
  }
}

m = accumulator, v = current , i = index

m = 累加器,v = 当前,i = 索引

Environment: TypeScript, ES6

环境:打字稿,ES6

回答by Anton Harald

function getLatestDate(data) {
   // convert to timestamp and sort
   var sorted_ms = data.map(function(item) {
      return new Date(item.MeasureDate).getTime()
   }).sort(); 
   // take latest
   var latest_ms = sorted_ms[sorted_ms.length-1];
   // convert to js date object 
   return new Date(latest_ms);
}

var data = [{MeasureDate: "2014-10-04T16:10:00"},
            {MeasureDate: "2013-10-04T16:10:00"},
            {MeasureDate: "2012-10-04T16:10:00"}];

getLatestDate(data).toString(); // "Sat Oct 04 2014 18:10:00 GMT+0200 (CEST)"

This function returns the latest date as a JavaScript date Object. You can also turn it into an ISO-String (the format of your source data) with the Date-Object method toISOString().

此函数将最新日期作为 JavaScript 日期对象返回。您还可以使用日期对象方法 toISOString() 将其转换为 ISO 字符串(源数据的格式)。

var date_str = "2012-10-04T16:10:00";
(new Date(date_str)).toISOString(); // "2012-10-04T16:10:00.000Z"

As you can see the result of the method includes always zero milliseconds in the end. If you need your original ISO data-string as a result, you may want to go with the following function:

如您所见,该方法的结果最终始终包含零毫秒。如果您因此需要原始 ISO 数据字符串,您可能需要使用以下功能:

function getLatestDate2(data) {

   var sorted = data.map(function(item) {
      var MeasureDate = item.MeasureDate;
      return {original_str: MeasureDate,
              in_ms: (new Date(MeasureDate)).getTime()}
   }).sort(function(item1, item2) {
      return (item1.in_ms < item2.in_ms)
   }); 

   // take latest
   var latest = sorted[0];

   return latest.original_str;
}

getLatestDate2(data); // "2014-10-04T16:10:00"

回答by Anton Harald

Inspired by many of the suggestions and comments in this thread, here is another solution for the problem. It's very fast, since there is no date object convertion.

受到该线程中许多建议和评论的启发,这里是该问题的另一种解决方案。它非常快,因为没有日期对象转换。

function getLatestDate(xs) {
   if (xs.length) {
      return xs.reduce((m, i) => (i.MeasureDate > m) && i || m, "")
               .MeasureDate;
   }
 }

Here's a version for Browser's not supporting arrow functions:

这是浏览器不支持箭头功能的版本:

function getLatestDateSave(xs) {
   if (xs.length) {
      return xs.reduce(function(m, i) {
         return (i.MeasureDate > m) && i || m;
      }, "").MeasureDate;
   }
 }

回答by Trebblez

Also further to @TravisHeeter's answer..

也进一步@TravisHeeter的回答..

Instead of using 'filter' and grabbing the array index of [0], you can use the .find() method instead as follows:

您可以使用 .find() 方法代替使用 'filter' 并获取 [0] 的数组索引,如下所示:

....

const mostRecentObject = a.find( e => { 
    const d = new Date( e.MeasureDate ); 
    return d.getTime() == mostRecentDate.getTime();
});

This also makes the code more performant, as it will stop looking after it has found the result, rather than filter which will iterate over all objects in the array.

这也使代码更高效,因为它会在找到结果后停止查找,而不是过滤器将迭代数组中的所有对象。

回答by Idrees Ramzan

        var dates = []; 

        dates.push(new Date("2019/06/25")); 
        dates.push(new Date("2019/06/26")); 
        dates.push(new Date("2019/06/27")); 
        dates.push(new Date("2019/06/28")); 

        function GFG_Fun() { 
            var maximumDate=new Date(Math.max.apply(null, dates)); 
            var minimumDate=new Date(Math.min.apply(null, dates)); 
        }