Skip to content
Advertisement

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

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement