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:00:00",…} 4:{date: "2016-11-22T00:00:00",…} 5:{date: "2016-11-23T00:00:00",…}
In this example the array is missing this date:
{date: "2016-11-20T00:00:00",…}
What is the best way to find a missing day from an array of dates in Javascript or Angular?
So that I later would be able to pass it to a datepicker as a disabled day.
Advertisement
Answer
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){ return Date.parse(a.date) - Date.parse(b.date); }).reduce(function(hash){ return function(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(new Date(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;}