var arr = [{
date : "2016/1/26",
count: 6
},
{
date : "2016/1/31",
count: 2
},
{
date : "2016/2/2",
count: 4
}]
I need to have all the dates (each day) inside the array from the current minimal date to the current max date. If the day does not exist, i need to add a new object with count=0.
The array is already sorted by date.
In my example, the array should be converted to:
arr = [{
date : "2016/1/26",
count: 6
},
{
date : "2016/1/27",
count: 0
},
{
date : "2016/1/28",
count: 0
},
{
date : "2016/1/29",
count: 0
},
{
date : "2016/1/30",
count: 0
},
{
date : "2016/1/31",
count: 2
},
{
date : "2016/2/1",
count: 0
},
{
date : "2016/2/2",
count: 4
}]
My approach:
for (i = 0; i < arr.length-1; i++) {
var prev = new Date(arr[i].date);
var next = new Date(arr[i+1].date);
if (prev.setTime(prev.getTime() + 86400000) != next) {
//86400000 equals a day in miliseconds
arr.splice(i+1, 0, {date: prev, count: 0});
}
}
This makes an infinite loop? The website gets stuck..