Find Missing Day From Array Of Dates Javascript
I am getting an array of day dates from an API: 0:{date: '2016-11-17T00:00:00',…} 1:{date: '2016-11-18T00:00:00',…} 2:{date: '2016-11-19T00:00:00',…} 3:{date: '2016-11-21T00:
Solution 1:
Check this out:
First you can sort the array (in case it is not so) using
Array.prototype.sort
Then use
Array.prototype.reduce
and ahash table
to find the missing dates
Demo given in snippet below:
var array=[
{date:"2016-11-17T00:00:00"},
{date:"2016-11-19T00:00:00"},
{date:"2016-11-18T00:00:00"},
{date:"2016-11-21T00:00:00"},
{date:"2016-11-22T00:00:00"},
{date:"2016-11-23T00:00:00"},
{date:"2016-11-27T00:00:00"}
];
var result = array.sort(function(a,b){
returnDate.parse(a.date) - Date.parse(b.date);
}).reduce(function(hash){
returnfunction(p,c){
var missingDaysNo = (Date.parse(c.date) - hash.prev) / (1000 * 3600 * 24);
if(hash.prev && missingDaysNo > 1) {
for(var i=1;i<missingDaysNo;i++)
p.push(newDate(hash.prev+i*(1000 * 3600 * 24)));
}
hash.prev = Date.parse(c.date);
return p;
};
}(Object.create(null)),[]);
console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}
Solution 2:
Create a new array missingDates[]
Iterate over the array (from your API) using a for loop
for (i = 0; i < array.length; i++){
var date1 = convert your array item (with index i) to a date
var date2 = convert your array item (with index i + 1) to a date (keep in mind, index i + 1 cant be > than array.length)
//calculate diffDays between the 2 dates, if diff is > 1, you have a missing datevar missingDate = create your missing date (useyourdate1variable + 1Day)
//addmisingDatetomissingDates[] arraymissingDates.push(missingDate)
}
Solution 3:
You can do a method getMissingDate
to return null
if there is not missing date or return the Date
object if there is a difference between to dates bigger than one day:
var arr1 = [{date: "2016-11-17T00:00:00"}, {date: "2016-11-18T00:00:00"}, {date: "2016-11-19T00:00:00"}, {date: "2016-11-21T00:00:00"}, {date: "2016-11-22T00:00:00"}, {date: "2016-11-23T00:00:00"}],
arr2 = [{date: "2016-11-17T00:00:00"}, {date: "2016-11-18T00:00:00"}, {date: "2016-11-19T00:00:00"}, {date: "2016-11-20T00:00:00"}, {date: "2016-11-21T00:00:00"}, {date: "2016-11-22T00:00:00"}, {date: "2016-11-23T00:00:00"}],
getMissingDate = function(arr) {
var result = null;
for (var i = 0, l = arr.length - 1; i < l; i++) {
var current = newDate(arr[i].date),
next = newDate(arr[i + 1].date);
if (1 < Math.ceil(Math.abs(next.getTime() - current.getTime()) / (1000 * 3600 * 24))) {
result = newDate(current.setDate(current.getDate() + 1));
break;
}
}
return result;
};
console.log('arr1:', getMissingDate(arr1));
console.log('arr2:', getMissingDate(arr2));
Post a Comment for "Find Missing Day From Array Of Dates Javascript"