Reputation: 7472
Let's say I have an array of N dates:
var dates = ['2013-01-01', '2013-01-02', '2013-01-05' ...]
What is the quickest way to find all the missing dates between the first date and the last? (let's assume that the dates are sorted from earliest to latest).
The gap is not consistent and could be at any size.
I rather not use any libraries, just pure javascript.
Upvotes: 0
Views: 714
Reputation: 171351
I would do a date diff, and generate new dates for any missing ones, like this:
var dates = [new Date(2013,1,1), new Date(2013,1,2), new Date(2013,1,5)];
var missingDates = [];
for (var i = 1; i < dates.length; i++)
{
var daysDiff = ((dates[i] - dates[i - 1]) / 86400000) - 1;
for (var j = 1; j <= daysDiff; j++)
{
var missingDate = new Date(dates[i - 1]);
missingDate.setDate(dates[i - 1].getDate() + j);
missingDates.push(missingDate);
}
}
console.log(missingDates);
Upvotes: 0
Reputation: 27823
Generally if you have two sorted arrays and want to find the items in one missing from the other you would iterate over both in paralel. My solution is similar to that one, but uses a generator over the date array:
function DateIterator(date){
this.current = date;
}
DateIterator.prototype.next = function() {
this.current.setDate(this.current.getDate() + 1);
return this.current.getFullYear() + '-' +
(this.current.getMonth()+1) + '-' +
this.current.getDate();
};
var dates = ['2013-1-1', '2013-1-2', '2013-1-5' ,'2013-2-2'];
var di = new DateIterator(new Date(dates[0]));
var date, missing = [];
for (var i=1; i<dates.length; i++) {
while ((date = di.next()) !== dates[i]) {
missing.push(date);
}
}
console.log(missing);
Note that the check for dates is made by comparing the string values. The dates returned by next are not 0-padded so a comparison between 2013-01-01 and 2013-1-1 would fail. This can be solved by making a smarter comparison function, but i consider it beyond the scope of the question.
Upvotes: 2