【问题标题】:Remove duplicated items from array-object that is inside another array从另一个数组内的数组对象中删除重复项
【发布时间】:2021-08-06 18:51:18
【问题描述】:

我正在尝试从一个数组对象中删除重复项,该数组对象是另一个数组中的属性。

我不想删除所有重复项,但只保留一个唯一的。

我有这个数组:

const arr = [
  {
    foo: "test",
    bar: [
      {
        address: "Duplicated",
        port: 100001,
      },
    ],
  },
  {
    foo: "Test2",
    bar: [
      {
        address: "Duplicated",
        port: 100000,
      } /*Remove this duplicate in every property bar but only by the property `address` */,
      {
        address: "Not duplicated",
        port: 100000,
      }
    ],
  },
];

输出会是这样的:

[
  {
    foo: "test",
    bar: [
      {
        address: "Duplicated",
        port: 100001,
      },
    ],
  },
  {
    foo: "Test2",
    bar: [
      {
        address: "Not duplicated",
        port: 100000,
      },
    ],
  },
];

我尝试了几件事,但都没有成功,我对此感到非常困惑。

【问题讨论】:

  • 请包含您尝试过的代码。您将获得有关您实际缺少的内容的反馈,而不仅仅是适用于这种情况的代码。

标签: javascript arrays typescript


【解决方案1】:

const arr = [
  {
    foo: "test",
    bar: [
      { address: "Duplicated", port: 100000 }
    ]
  },
  {
    foo: "Test2",
    bar: [
      { address: "Duplicated", port: 100000 },
      { address: "Not duplicated", port: 100000 }
    ]
  }
];

// initialize empty Set
const addressSet = new Set();
// iterate over arr
const res = arr.map(item => {
  const current = {...item};
  // filter current item's bar list
  current.bar = current.bar.filter(({ address }) => 
    // if address is in set remove it from arr, otherwise add it to the set
    addressSet.has(address) 
      ? false 
      : addressSet.add(address)
  );
  return current;
});

console.log(res);

【讨论】:

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