Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the earliest of a series of JavaScript dates

How do I find the earliest of a set of dates. Currently I have the following code which works just fine:

var dates = [date1,date2]; // list of javascript dates 
var start = moment(new Date(9999, 0, 1))
// I wished this was one line in momentjs + underscorejs
_.forEach(dates, (date) => {
      if (moment(date).isBefore(start)) {
            start = moment(date);
      }
});

I was hoping there was a neater way (in one line). I would prefer to use a simpler function in Underscore (min does not work on dates) / momentjs.

like image 905
basarat Avatar asked Aug 23 '13 04:08

basarat


2 Answers

I found _.min is reliable on moment instances. The following works:

    var dates = _.map([date1,date2],function(date){return moment(date)});
    var start = _.min(dates);    

nevermind.

like image 91
basarat Avatar answered Sep 23 '22 16:09

basarat


var earliest = new Date(Math.min.apply(null, dates))

see mdn Function.apply

Math.min(arg1,arg2,...argN) finds the lowest of N numeric arguments.

Because of how Function.prototype.apply works, Math.min.apply takes two arguments, a this setting, which appears to be unneeded here, and a arg array.

The numeric representation of a date is the ms since 1970. A date coerced to a number will yield this value. A new date object is initialized to this lowest value, which is the same date as the earliest date but not the same object.

This is similar to @fardjad's approach, but does not need the underscore.js library for _.min., and is shortened by the use of func.apply, which should be common javascript to most recent browsers.

like image 23
Paul Avatar answered Sep 25 '22 16:09

Paul