首页 > 解决方案 > 如何在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。我不知道该怎么做,任何帮助都会很棒。

标签: javascriptarraysreactjsfilter

解决方案


创建数组时,但在填充它们之前,有两个函数可以帮助初始化:

// 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. 完成后,您可以继续计数和更新数组。

参考:


推荐阅读