您将如何使用可包含 0 到 7 个元素的数组中的单循环生成缺失数据?

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

所以我有一个 API,其中 returns 我最近 7 天分配的水值,它可以包含一个空数组或一个值,例如:

[
  {
    day: Monday,
    waterDispensed: 40,
  },
  {
    day: Wednesday,
    waterDispensed: 83,
  },
  {
    day: Thursday,
    waterDispensed: 33,
  },
]

假设今天是星期四,我需要一个对象数组来填充缺失的最后 7 天数据:


[
  {
    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,
  },
]

考虑到您只需要使用一个循环,您会怎么做?您可以使用条件语句,但不能像新手那样使用。 可以使用数组方法,但要考虑时间复杂度。

首先创建一个包含您需要的星期几的数组。为此,您可以使用包含星期几的数组,将其加倍,然后切出与您需要的实际范围相对应的部分。

然后将其转换为具有 0 个值的对象数组,最后用您从响应中获得的对象覆盖该数组中的对象:

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