javascript - 如何在js中将数据推送到固定长度的数组
问题描述
我有一个像这样的对象数组。
[
{
channelName: "WhatsApp"
count: 1
date: "2021-06-05"
},{
channelName: "RCS"
count: 1
date: "2021-06-09"
}
]
频道名称有两种类型 1. WhatsApp 和 2nd 是 RCS。我想过滤掉具有特定通道名称的计数并将其存储在单独的数组中。但这里的问题是我希望两个数组长度应该相同。如果有 WhatsApp 的数据,那么它将添加计数,否则它将添加 0 来代替它。
为此,我做了这样的事情,但这不起作用。
const filterData = (data: any) => {
const category: any = [];
const whatsAppCount: any = [];
const rcsCount: any = [];
data.filter((item: any, i: number) => {
if (item.channelName === "WhatsApp") {
whatsAppCount[i] = item.count;
} else if (item.channelName === "RCS") {
rcsCount[i] = item.count;
}
category.push(item.date);
});
setGraphData({
category: category,
whatsApp: whatsAppCount,
rcs: rcsCount,
});
console.log("handleRun", { category, whatsAppCount, rcsCount });
};
在这里,控制台日志给出了类似的内容。
whatsAppCount: [1, 2, 13, 21, empty × 2, 8, 5, empty, 18, empty, 12, 4]
rcsCount: [empty × 4, 1, 12, empty × 2, 1, empty, 8]
在空的地方,我想要 0。我不知道该怎么做,任何帮助都会很棒。
解决方案
创建数组时,但在填充它们之前,有两个函数可以帮助初始化:
// create an array with 10 slots preallocated but empty (not `undefined`)
let arr = new Array(10);
// set all allocated slots to a value (`0` in this case)
arr = arr.fill(0);
由于您提前知道所需的长度,因此您可以使用它在构造时预先确定数组的大小。然后使用.fill
将值初始化为0
. 完成后,您可以继续计数和更新数组。
参考:
推荐阅读
- c++ - 如何实现 std::atomic 引用计数器?
- python - Python - 检查字符串中是否至少包含 3 个数字
- perl - 将文件从数字排序转换为字母排序
- javascript - React/nextJS:如何调试 SSR react 应用的不同节点?
- php - 无法从购物车页面获取自定义字段数据到 woocommerce 中订单的结帐页面
- android - gradle有没有替代品?
- python - 传递值列表以在 Python 中重新映射
- ios - segmentcontrol 没有在 ios swift 中选择
- vue.js - vue:向组件内部的“this”添加自定义属性,并防止添加“__ob__”和getter/setter
- javascript - 迭代槽数组并动态发送http请求