Reputation: 63
I have an array generated through a code where I'm calculating, for each day from now to 7 days ago, the daily occurrences. Right now my code is skipping the days where there aren't occurrences, but I would like to insert those days together with a 0 count value. Here's my code:
var myObj;
fetch('https://blahblahblah?'+param1+param2+"FromDate"+"="+moment().subtract(7,'d').format('YYYY-MM-DD'))
.then(res=>res.json())
.then(data=>myObj= data);
var myRes= [];
myObj.forEach(function (elem) {
var date = elem.CreatedDate.split(' ')[0];
if (myRes[date]) {
myRes[date] += 1;
} else {
myRes[date] = 1;
}
});
Right now I'm getting a similar result:
2020-12-11: 1
2020-12-12: 2
2020-12-13: 1
2020-12-15: 2
2020-12-16: 1
Because on 12-10 I didn't have any value and on 12-14 neither. Given the startTime moment().subtract(7,'d').format('YYYY-MM-DD')
how can I output the days with 0 values like in the format below?:
2020-12-10: 0
2020-12-11: 1
2020-12-12: 2
2020-12-13: 1
2020-12-14: 0
2020-12-15: 2
2020-12-16: 1
Thank you very much
Edit: here's my obj:
[{Id, Var1, Var2, CreationDate},
{1, 123, Var2, 2020-12-11},
{2, 1234, Var2, 2020-12-12},
{3, 12345, Var2, 2020-12-12},
{4, 1234, Var2, 2020-12-13},
{5, 321, Var2, 2020-12-15},
{6, 3214, Var2, 2020-12-15},
{7, 5432, Var2, 2020-12-16}]
Upvotes: 0
Views: 3366
Reputation: 5054
Once you calculate myRes You can create an array with last 7 days date and then compare with myRes to create finalResult with the missing dates.
let myRes = {
'2020-12-11': 1,
'2020-12-12': 2,
'2020-12-13': 1,
'2020-12-15': 2,
'2020-12-16': 1,
}
const dates = [];
const NUM_OF_DAYS = 7; // get last 7 dates.
for (let i = 0; i < NUM_OF_DAYS; i++) {
let date = moment();
date.subtract(i, 'day');
dates.push(date.format('YYYY-MM-DD'));
}
let finalResult = {};
dates.reverse().forEach(date => {
if(!myRes.hasOwnProperty(date)) {
finalResult[date] = 0;
} else {
finalResult[date] = myRes[date];
}
});
console.log(finalResult);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
Upvotes: 2
Reputation: 156
Does this change work for you?
var myRes= new Array(7).fill(0);
Upvotes: 1