Min/Max of dates in an array?

JavascriptDateMaxMin

Javascript Problem Overview


How can I find out the min and the max date from an array of dates? Currently, I am creating an array like this:

var dates = [];
dates.push(new Date("2011/06/25"))
dates.push(new Date("2011/06/26"))
dates.push(new Date("2011/06/27"))
dates.push(new Date("2011/06/28"))

Is there a built-in function to do this or am I to write my own?

Javascript Solutions


Solution 1 - Javascript

Code is tested with IE,FF,Chrome and works properly:

var dates=[];
dates.push(new Date("2011/06/25"))
dates.push(new Date("2011/06/26"))
dates.push(new Date("2011/06/27"))
dates.push(new Date("2011/06/28"))
var maxDate=new Date(Math.max.apply(null,dates));
var minDate=new Date(Math.min.apply(null,dates));

Solution 2 - Javascript

Something like:

var min = dates.reduce(function (a, b) { return a < b ? a : b; }); 
var max = dates.reduce(function (a, b) { return a > b ? a : b; });

Tested on Chrome 15.0.854.0 dev

Solution 3 - Javascript

_.min and _.max work on arrays of dates; use those if you're using Lodash or Underscore, and consider using Lodash (which provides many utility functions like these) if you're not already.

For example,

_.min([
    new Date('2015-05-08T00:07:19Z'),
    new Date('2015-04-08T00:07:19Z'),
    new Date('2015-06-08T00:07:19Z')
])

will return the second date in the array (because it is the earliest).

Solution 4 - Javascript

Same as apply, now with spread :

const maxDate = new Date(Math.max(...dates));

(could be a comment on best answer)

Solution 5 - Javascript

Since dates are converted to UNIX epoch (numbers), you can use Math.max/min to find those:

var maxDate = Math.max.apply(null, dates)
// convert back to date object
maxDate = new Date(maxDate)

(tested in chrome only, but should work in most browsers)

Solution 6 - Javascript

**Use Spread Operators| ES6 **

let datesVar = [ 2017-10-26T03:37:10.876Z,
  2017-10-27T03:37:10.876Z,
  2017-10-23T03:37:10.876Z,
  2015-10-23T03:37:10.876Z ]

Math.min(...datesVar);

That will give the minimum date from the array.

> Its shorthand Math.min.apply(null, ArrayOfdates);

Solution 7 - Javascript

ONELINER:

var min= dates.sort((a,b)=>a-b)[0], max= dates.slice(-1)[0];

result in variables min and max, complexity O(nlogn), editable example here. If your array has no-date values (like null) first clean it by dates=dates.filter(d=> d instanceof Date);.

var dates = [];
dates.push(new Date("2011-06-25")); // I change "/" to "-" in "2011/06/25"
dates.push(new Date("2011-06-26")); // because conosle log write dates 
dates.push(new Date("2011-06-27")); // using "-".
dates.push(new Date("2011-06-28"));

var min= dates.sort((a,b)=>a-b)[0], max= dates.slice(-1)[0];

console.log({min,max});

Solution 8 - Javascript

var max_date = dates.sort(function(d1, d2){
    return d2-d1;
})[0];

Solution 9 - Javascript

The above answers do not handle blank/undefined values to fix this I used the below code and replaced blanks with NA :

function getMax(dateArray, filler) {
      filler= filler?filler:"";
      if (!dateArray.length) {
        return filler;
      }
      var max = "";
      dateArray.forEach(function(date) {
        if (date) {
          var d = new Date(date);
          if (max && d.valueOf()>max.valueOf()) {
            max = d;
          } else if (!max) {
            max = d;
          }
        }
      });
      return max;
    };
console.log(getMax([],"NA"));
console.log(getMax(datesArray,"NA"));
console.log(getMax(datesArray));

function getMin(dateArray, filler) {
 filler = filler ? filler : "";
  if (!dateArray.length) {
    return filler;
  }
  var min = "";
  dateArray.forEach(function(date) {
    if (date) {
      var d = new Date(date);
      if (min && d.valueOf() < min.valueOf()) {
        min = d;
      } else if (!min) {
        min = d;
      }
    }
  });
  return min;
}

console.log(getMin([], "NA"));
console.log(getMin(datesArray, "NA"));
console.log(getMin(datesArray));

I have added a plain javascript [demo here][1] and used it as a filter with AngularJS in [this codepen][2]

[1]: https://codepen.io/samdeesh/pen/MrppEx?editors=0011#0 "Demo" [2]: https://codepen.io/samdeesh/pen/jLJZxP

Solution 10 - Javascript

if you get max or min date with string type from string date of array,you can try this:

const dates = ["2021-02-05", "2021-05-20", "2021-01-02"]
const min = dates.reduce((acc,date)=>{return acc&&new Date(acc)<new Date(date)?acc:date},'')
const max = dates.reduce((acc,date)=>{return acc&&new Date(acc)>new Date(date)?acc:date},'')

Solution 11 - Javascript

This is a particularly great way to do this (you can get max of an array of objects using one of the object properties): Math.max.apply(Math,array.map(function(o){return o.y;}))

This is the accepted answer for this page: https://stackoverflow.com/questions/4020796/finding-the-max-value-of-an-attribute-in-an-array-of-objects

Solution 12 - Javascript

Using Moment, Underscore and jQuery, to iterate an array of dates.

Sample JSON:

"workerList": [{		
		"shift_start_dttm": "13/06/2017 20:21",
		"shift_end_dttm": "13/06/2017 23:59"
	}, {
		"shift_start_dttm": "03/04/2018 00:00",
		"shift_end_dttm": "03/05/2018 00:00"		
	}]

Javascript:

function getMinStartDttm(workerList) {	
	if(!_.isEmpty(workerList)) {
		var startDtArr = [];
		$.each(d.workerList, function(index,value) {				
			startDtArr.push(moment(value.shift_start_dttm.trim(), 'DD/MM/YYYY HH:mm'));	
		 });			
		 var startDt = _.min(startDtArr);			
		 return start.format('DD/MM/YYYY HH:mm');
	} else {
		return '';
	}	
}

Hope it helps.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLegendView Question on Stackoverflow
Solution 1 - JavascriptAndrew D.View Answer on Stackoverflow
Solution 2 - Javascriptuser180100View Answer on Stackoverflow
Solution 3 - JavascriptMark AmeryView Answer on Stackoverflow
Solution 4 - JavascriptlvdView Answer on Stackoverflow
Solution 5 - JavascriptRicardo TomasiView Answer on Stackoverflow
Solution 6 - JavascriptRudresh AjgaonkarView Answer on Stackoverflow
Solution 7 - JavascriptKamil KiełczewskiView Answer on Stackoverflow
Solution 8 - Javascriptwong2View Answer on Stackoverflow
Solution 9 - JavascriptSamdeeshView Answer on Stackoverflow
Solution 10 - JavascriptserenasView Answer on Stackoverflow
Solution 11 - Javascriptuser5292841View Answer on Stackoverflow
Solution 12 - JavascriptSiva AnandView Answer on Stackoverflow