How to find the earliest date in an array using JavaScript
javascript
Solution
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:
- `Date.parse()`.
- `Array.prototype.reduce()`.
- `Array.prototype.sort()`.
Problem
How can I find the earliest date, i.e. minimum date, in an array using JavaScript? Example: ``` ["10-Jan-2013", "12-Dec-2013", "1-Sep-2013", "15-Sep-2013"] ``` My output should be: ``` ["10-Jan-2013", "1-Sep-2013", "15-Sep-2013", "12-Dec-2013"] ``` How can I do this?