Per Ström Per Ström - 3 months ago 9
Javascript Question

Get most recent date, underscore

Got this:

[{
"title": "qq",
"dateValuePair": {
"date": "2016-04-29T22:00:00.000Z",
"value": 243500.3491
}
},
{
"title_sv": "ccc",
"dateValuePair": {
"date": "2016-03-29T22:00:00.000Z",
"value": 243500.3491
}
}]


I need a function that returns the object with the most recent date.

{
"title_sv": "ccc",
"dateValuePair": {
"date": "2016-03-29T22:00:00.000Z",
"value": 243500.3491
}
}


Is there some neat one line underscore trick to do this?

Answer

You can use _.max:

var array = [{
  "title": "qq",
    "dateValuePair": {
      "date": "2016-04-29T22:00:00.000Z",
      "value": 243500.3491
     }
  },
  {
    "title_sv": "ccc",
    "dateValuePair": {
      "date": "2016-03-29T22:00:00.000Z",
      "value": 243500.3491
     }
 }];

var result = _.max(array, function(el) { 
  return new Date(el.dateValuePair.date).getTime();
});
Comments