How do I return the lowest date value and the highest date value of an array in Javascript?

advertisements

How to return the lowest date value and highest date value from an array?

For example for the below array, I'd like to create a function that returns the lowest date, as well as another function that returns the highest date?

var data = [
  {date: "2011-11-01T16:17:54Z", quantity: 2, total: 190, tip: 100, type: "tab"},
  {date: "2011-11-14T16:20:19Z", quantity: 2, total: 190, tip: 100, type: "tab"},
  {date: "2011-11-14T16:28:54Z", quantity: 1, total: 300, tip: 200, type: "visa"},
  {date: "2011-11-14T16:30:43Z", quantity: 2, total: 90, tip: 0, type: "tab"},
  {date: "2011-11-14T16:48:46Z", quantity: 2, total: 90, tip: 0, type: "tab"},
  {date: "2011-11-14T16:53:41Z", quantity: 2, total: 90, tip: 0, type: "tab"},
  {date: "2011-11-14T16:54:06Z", quantity: 1, total: 100, tip: 0, type: "cash"},
  {date: "2011-11-14T16:58:03Z", quantity: 2, total: 90, tip: 0, type: "tab"},
  {date: "2011-11-14T17:07:21Z", quantity: 2, total: 90, tip: 0, type: "tab"},
  {date: "2011-11-14T17:22:59Z", quantity: 2, total: 90, tip: 0, type: "tab"},
  {date: "2011-11-14T17:25:45Z", quantity: 2, total: 200, tip: 0, type: "cash"},
  {date: "2011-11-31T17:29:52Z", quantity: 1, total: 200, tip: 100, type: "visa"}
];

I'm not sure if this is relevant, but I am using this array with crossfilter, so I'm not sure if crossfilter has any helpful methods.


We just have to apply some Javascript Magic.

var result = Math.max.apply( null, data.map(function( v ) {
    return +new Date( v.date );
}));

There, we map those Objects into just their timestamp representation from the ISO-Date string. Then we simply apply a Math.max, respectively Math.min on the resulting Array. All we have left to do now, is to re-convert that timestamp into a Date object

new Date( result );


And just for the heck of it, an alternative solution using Array.prototype.reduce and pure String comparison (if you are scared of browser incompatibilities on parsing ISO Date Strings).

var max = data.reduce(function( prev, current ) {
  return prev.date > current.date ? prev : current;
});
// for the min version just ">" to "<"