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?
Note. In an array, the first element has index (position) 0, the second has index 1, ...
To check if a date is contained in an array:Use the find() method to iterate over the array. On each iteration, check if the date's timestamp is equal to a specific value. If the date is not found, the find method returns undefined .
var date1 = new Date(); date1. setFullYear(2011, 6, 1); // 2011-07-01, ok console. log(date1); // set date2 the same date as date1 var date2 = date1; // ... // now I'm gonna set a new date for date2 date2. setFullYear(2011, 9, 8); // 2011-10-08, ok console.
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()
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With