【问题标题】:js remove duplicate from array of objects by values and count duplicatesjs 按值从对象数组中删除重复项并计算重复项
【发布时间】:2021-01-23 10:04:02
【问题描述】:

我有一个对象数组

const data=[
  {typeId: 1, sort: 1, name: "Test1"},
  {typeId: 2, sort: 1, name: "Test2"},
  {typeId: 1, sort: 2, name: "Test3"},
  {typeId: 3, sort: 1, name: "Test4"},
];

我想通过键“typeId”删除重复项,并且键“sort”值更大。我想添加键“计数” - 对象按 typeId 重复多少次。

这就是我想要实现的目标:

const answer=[
  {typeId: 1, sort: 1, name: "Test1", count: 2},
  {typeId: 2, sort: 1, name: "Test2", count: 1},
  {typeId: 3, sort: 1, name: "Test4", count: 1},
];

我该怎么做?

【问题讨论】:

    标签: javascript arrays object duplicates counting


    【解决方案1】:

    这种方法适用于sort 的任何值。

    const data = [
      {typeId: 1, sort: 1, name: "Test1"},
      {typeId: 2, sort: 1, name: "Test2"},
      {typeId: 1, sort: 2, name: "Test3"},
      {typeId: 3, sort: 1, name: "Test4"},
    ];
    
    const answer = Object.values(data.reduce((p, v) => {
      const old = p[v.typeId];
      if (!old)
        p[v.typeId] = { ...v, count: 1 };
      else if (old.sort > v.sort)
        p[v.typeId] = { ...v, count: old.count + 1 };
      else
        p[v.typeId].count++;
      return p;
    }, {}));
    
    console.log(answer);

    【讨论】:

      【解决方案2】:

      您可以将对象按typeId 分组并递增count

      此方法假定sort 的最小值始终为一。

      const 
          data = [{ typeId: 1, sort: 1, name: "Test1" }, { typeId: 2, sort: 1, name: "Test2" }, { typeId: 1, sort: 2, name: "Test3" }, { typeId: 3, sort: 1, name: "Test4" }],
          result = Object.values(data.reduce((r, o) => {
              if (r[o.typeId]) r[o.typeId].count++;
              else r[o.typeId] = { ...o, sort: 1, count: 1 };
              return r;
          }, {}));
      
      console.log(result);
      .as-console-wrapper { max-height: 100% !important; top: 0; }

      【讨论】:

        猜你喜欢
        • 2017-04-10
        • 2022-01-24
        • 1970-01-01
        • 1970-01-01
        • 2019-02-28
        • 1970-01-01
        • 1970-01-01
        • 2016-03-12
        相关资源
        最近更新 更多