gpt4 book ai didi

JavaScript 为数组中不存在的键添加零

转载 作者:行者123 更新时间:2023-12-01 15:59:39 25 4
gpt4 key购买 nike

我有两个数组:

date_array = ["2020-02-27", "2020-02-28", "2020-02-29", "2020-03-01", "2020-03-02", "2020-03-03", "2020-03-04", "2020-03-05", "2020-03-06", "2020-03-07", "2020-03-08", "2020-03-09", "2020-03-10", "2020-03-11", "2020-03-12", "2020-03-13", "2020-03-14", "2020-03-15", "2020-03-16", "2020-03-17", "2020-03-18", "2020-03-19", "2020-03-20", "2020-03-21", "2020-03-22", "2020-03-23", "2020-03-24", "2020-03-25", "2020-03-26", "2020-03-27"]

count_array=[{date: "2020-03-22", count: 310},
{date: "2020-03-23", count: 115},
{date: "2020-03-24", count: 78},
{date: "2020-03-25", count: 29},
{date: "2020-03-26", count: 36},
{date: "2020-03-27", count: 3}]

我需要创建第三个数组,其中包含 30 个仅具有计数值的元素,如果当天不存在计数,则返回 0。我如何实现这一点?

我试过:

date_array.forEach(element => {
if (
data[date_array.indexOf(element)].date ==
date_array[element]
) {
target_array.push(data[data.indexOf(element)].count_array);
} else {
target_array.push(0);
}
});

但我收到“无法读取未定义的属性‘日期’”

最佳答案

为了降低计算复杂度,首先将数组转换为以日期为索引的对象。然后,要制作输出数组,只需 .map date_array 通过查找对象上的日期,与 0 交替:

date_array = ["2020-02-27", "2020-02-28", "2020-02-29", "2020-03-01", "2020-03-02", "2020-03-03", "2020-03-04", "2020-03-05", "2020-03-06", "2020-03-07", "2020-03-08", "2020-03-09", "2020-03-10", "2020-03-11", "2020-03-12", "2020-03-13", "2020-03-14", "2020-03-15", "2020-03-16", "2020-03-17", "2020-03-18", "2020-03-19", "2020-03-20", "2020-03-21", "2020-03-22", "2020-03-23", "2020-03-24", "2020-03-25", "2020-03-26", "2020-03-27"]
count_array=[{date: "2020-03-22", count: 310},
{date: "2020-03-23", count: 115},
{date: "2020-03-24", count: 78},
{date: "2020-03-25", count: 29},
{date: "2020-03-26", count: 36},
{date: "2020-03-27", count: 3}]

const countsByDate = Object.fromEntries(
count_array.map(({ date, count }) => [date, count])
);
const output = date_array.map(date => countsByDate[date] || 0);
console.log(output);

关于JavaScript 为数组中不存在的键添加零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60883156/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com