Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

167
Views
How would you generate missing data using single loop from an array which can contain from 0 to 7 elements?

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!