So I have an API which returns me the value of water dispensed for the last 7 days and it can contain an empty array or a value such as:
[ { day: Monday, waterDispensed: 40, }, { day: Wednesday, waterDispensed: 83, }, { day: Thursday, waterDispensed: 33, }, ]
Assuming today is Thursday and I need an array of objects which would fill missing last 7 days data as:
[ { day: Friday, // 25th Feb waterDispensed: 0, }, { day: Saturday, // 26th Feb waterDispensed: 0, }, { day: Sunday, // 27th Feb waterDispensed: 0, }, { day: Monday, waterDispensed: 40, }, { day: Tuesday, waterDispensed: 0, }, { day: Wednesday, waterDispensed: 83, }, { day: Thursday, // 3rd March waterDispensed: 33, }, ]
How would you do this considering that you need to use only one loop? You can use conditional statements but not like a newbie.
You can use array methods but should consider time complexity.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
First create an array of the week days you need. For this, you can use an array with the days of the week, double it, and then slice out the part that corresponds to the actual range you need.
Then turn that into an object array with 0 values, and finally overwrite the objects in that array with the objects that you got from the response:
const dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
function fillWeek(date, data) {
const weekday = date.getDay();
const week = dayNames.concat(dayNames).slice(weekday + 1, weekday + 8);
let result = week.map(day => ({day, waterDispensed: 0 }));
for (let obj of data) result[week.indexOf(obj.day)] = obj;
return result;
}
const data = [
{ day: "Monday", waterDispensed: 40 },
{ day: "Wednesday", waterDispensed: 83 },
{ day: "Thursday", waterDispensed: 33 },
]
// Let's assume a Thursday (3 March 2022 is a Thursday):
let result = fillWeek(new Date(2022, 2, 3), data);
console.log(result);
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0