I'd suggest passing an anonymous function to the sort()
method:
var dates = ['10-Jan-2013','12-Dec-2013','1-Sep-2013','15-Sep-2013'],
orderedDates = dates.sort(function(a,b){
return Date.parse(a) > Date.parse(b);
});
console.log(orderedDates); // ["10-Jan-2013", "1-Sep-2013", "15-Sep-2013", "12-Dec-2013"]
var dates = ['10-Jan-2013', '12-Dec-2013', '1-Sep-2013', '15-Sep-2013'],
orderedDates = dates.sort(function(a, b) {
return Date.parse(a) > Date.parse(b);
});
console.log(orderedDates);
JS Fiddle demo.
Note the use of an array ['10-Jan-2013','12-Dec-2013','1-Sep-2013','15-Sep-2013']
of quoted date-strings.
The above will give you an array of dates, listed from earliest to latest; if you want only the earliest, then use orderedDates[0]
.
A revised approach, to show only the earliest date – as requested in the question – is the following:
var dates = ['10-Jan-2013', '12-Dec-2013', '1-Sep-2013', '15-Sep-2013'],
earliest = dates.reduce(function (pre, cur) {
return Date.parse(pre) > Date.parse(cur) ? cur : pre;
});
console.log(earliest); // 10-Jan-2013
var dates = ['10-Jan-2013', '12-Dec-2013', '1-Sep-2013', '15-Sep-2013'],
earliest = dates.reduce(function(pre, cur) {
return Date.parse(pre) > Date.parse(cur) ? cur : pre;
});
console.log(earliest);
JS Fiddle demo.
References: