Math.min
/max
only compares numbers, not strings. Don't use them to represent the dates, but use Date
objects - they will be compared by their internal timestamp number. Still, the max/min will return that internal number, so you would need to convert it back to a Date
(see Min/Max of dates in an array?):
However, if you want to use the strings or can't use the recreated Date, you will need to run manually through the array - either with a for-loop, or the ES5.1-only iterator method .reduce()
:
var min = datestrings.reduce(function(min, cur) {
return cur < min ? cur : min;
});
// is equivalent to
var min = datestrings[0];
for (var i=1; i<datestrings.length; i++)
if (datestrings[i] < min)
min = datestrings[i];
If your code does not need to be efficient, you also just can sort the array and get the first and last values. The default alphanumeric sorting will do it for your date format, so this is really simple:
datestrings.sort();
var min = datestrings[0],
max = datestrings[datestrings.lengh-1];