A set of objects returns the highest global value from the last date

advertisements

I have a similar structure:

var array = [
  {
    "overall": 8,
    "date": "2016-03-15",
    "review": "bla bla",
  },
  {
    "overall": 6,
    "date": "2016-01-19",
    "review": "asfasfsadfsd",
  },
  {
    "overall": 7,
    "date": "2016-01-23",
    "review": "adfsasfdasfas",
  }];

This return the highest value:

var highestScore = Math.max.apply(Math,array.map(function(o){return o.overall;}));

How can I filter this array to obtain the review that relates to highest overall value from the latest date? In this case "bla bla"


There is no need to sort the array, since you want to get only the highest value. So use reduce() and for comparing date string parse it using Date.parse() .

var array = [{
  "overall": 5,
  "date": "2016-03-15",
  "review": "sadas sasdadasdas",
}, {
  "overall": 6,
  "date": "2016-01-19",
  "review": "asfasfsadfsd",
}, {
  "overall": 9,
  "date": "2016-03-15",
  "review": "sadas sasdadasdas",
}, {
  "overall": 7,
  "date": "2016-01-23",
  "review": "adfsasfdasfas",
}];

var res = array.reduce(function(a, b) {
  // parse the date
  var d1 = Date.parse(a.date),
    d2 = Date.parse(b.date);
  // if dates are equal compare value of overall and return value , else return based on date
  return d1 == d2 ? (a.overall > b.overall ? a : b) : (d1 > d2 ? a : b);
}).overall; // get overall value from final object

document.write(res);