如何使用单个循环从可包含 0 到 7 个元素的数组中生成缺失数据?
因此,我有一个 API,它返回过去 7 天分配的水的值,它可以包含一个空数组或一个值,例如:
[
{
day: Monday,
waterDispensed: 40,
},
{
day: Wednesday,
waterDispensed: 83,
},
{
day: Thursday,
waterDispensed: 33,
},
]
假设今天是星期四,我需要一个对象数组来填充过去 7 天缺失的数据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,
},
]
考虑到您只需要使用一个循环,您将如何做到这一点?您可以使用条件语句,但不像新手那样。 您可以使用数组方法,但应考虑时间复杂度。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先创建一个您需要的工作日数组。为此,您可以使用包含星期几的数组,将其加倍,然后切出与您需要的实际范围相对应的部分。
然后将其转换为值为 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: