【问题标题】:Display number of items from array of objects without duplicate显示对象数组中的项目数而不重复
【发布时间】:2020-10-06 09:41:06
【问题描述】:

我正在学习 javascript,但遇到了一些问题。 我想迭代一个对象数组,但有一些“选项”:

  • 不显示重复项。
  • 显示项目数。

预期结果:

received 1

missed 2

dialed 3

我知道如何迭代一个对象数组并使用.length 显示每个项目的数量,但我不知道迭代+显示数量+删除重复项...你能帮我吗?

const calls = [
  {
    type: "missed",
    date: "xx-xx-xx"
  },
  {
    type: "received",
    date: "xx-xx-xx"
  },
  {
    type: "dialed",
    date: "xx-xx-xx"
  },
  {
    type: "missed",
    date: "xx-xx-xx"
  },
  {
    type: "dialed",
    date: "xx-xx-xx"
  },
  {
    type: "dialed",
    date: "xx-xx-xx"
  }
];

【问题讨论】:

    标签: javascript arrays loops object duplicates


    【解决方案1】:

    一个很好的分组项目的方法是使用reduce(它也很灵活,所以如果你添加其他类型也没有问题):

    const calls = [{
        type: "missed",
        date: "xx-xx-xx"
      },
      {
        type: "received",
        date: "xx-xx-xx"
      },
      {
        type: "dialed",
        date: "xx-xx-xx"
      },
      {
        type: "missed",
        date: "xx-xx-xx"
      },
      {
        type: "dialed",
        date: "xx-xx-xx"
      },
      {
        type: "dialed",
        date: "xx-xx-xx"
      }
    ];
    
    const output = calls.reduce((aggObj, item) => {
        if(!aggObj[item.type]){
            aggObj[item.type] = 0
        }
        aggObj[item.type] += 1;
        return aggObj;
    }, {});
    //output as object:
    console.log(output);
    
    //output as array:
    const outArr = Object.entries(output);
    console.log(outArr);
    
    //output as strings:
    outArr.forEach(([k,v]) => console.log(k,v));

    【讨论】:

      【解决方案2】:

      const calls = [{
          type: "missed",
          date: "xx-xx-xx"
        },
        {
          type: "received",
          date: "xx-xx-xx"
        },
        {
          type: "dialed",
          date: "xx-xx-xx"
        },
        {
          type: "missed",
          date: "xx-xx-xx"
        },
        {
          type: "dialed",
          date: "xx-xx-xx"
        },
        {
          type: "dialed",
          date: "xx-xx-xx"
        }
      ];
      const types = ["missed", "received", "dialed"];
      types.forEach(type => {
        console.log(type + ": " + calls.filter((calls) => calls.type === type).length);
      });

      【讨论】:

        【解决方案3】:

        希望对你有帮助

        var newArr = calls.filter((x, index, self) =>
          index === self.findIndex((t) => (
            t.type === x.type && t.date === x.date)));
        
        console.log(newArr);

        【讨论】:

          猜你喜欢
          • 2014-03-10
          • 2019-06-23
          • 2017-11-10
          • 1970-01-01
          • 1970-01-01
          • 2021-03-10
          • 1970-01-01
          相关资源
          最近更新 更多