Home > database >  How would you generate missing data using single loop from an array which can contain from 0 to 7 el
How would you generate missing data using single loop from an array which can contain from 0 to 7 el

Time:03-03

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.

CodePudding user response:

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);

  • Related