【问题标题】:JavaScript - Array of Objects - Compare & Remove Duplicates ES6 [duplicate]JavaScript - 对象数组 - 比较和删除重复 ES6 [重复]
【发布时间】:2021-06-19 07:23:49
【问题描述】:

我有两个对象:

对象一

[
  { repo: 'edat-ims-github', status: 200 },
  { repo: 'edat-ims-github-spa', status: 200 },
  { repo: 'test-repo-three', status: 200 }
]

对象二

[
  { repo: 'edat-ims-github', status: 200 },
  { repo: 'edat-ims-github-spa', status: 200 },
  { repo: 'test-repo-one', status: 200 },
  { repo: 'test-repo-two', status: 200 },
  { repo: 'test-repo-three', status: 200 }
]

我想比较两个数组并从第二个数组中删除重复的对象,因此我的输出如下所示:

[
  { repo: 'test-repo-one', status: 200 },
  { repo: 'test-repo-two', status: 200 }
]

我尝试使用 ES6 来执行此操作:

  const result = objectTwo.filter((obj) => {
    return !objectOne.includes(obj);
  });

但是,结果的结果是:

[
  { repo: 'edat-ims-github', status: 200 },
  { repo: 'edat-ims-github-spa', status: 200 },
  { repo: 'test-repo-one', status: 200 },
  { repo: 'test-repo-two', status: 200 },
  { repo: 'test-repo-three', status: 200 }
]

有人可以指导我哪里出了问题以及实现这一目标的最佳方法是什么?在现实生活中,两个数组都有 10000 多个对象。

我没有测试相等性,因为两个数组不一样,我更多的是测试如何删除重复项。

谢谢:)

【问题讨论】:

    标签: javascript node.js loops ecmascript-6


    【解决方案1】:

    试试这个代码:

    obj1 = [
      { repo: 'edat-ims-github', status: 200 },
      { repo: 'edat-ims-github-spa', status: 200 },
      { repo: 'test-repo-three', status: 200 }
    ]
    
    obj2 = [
      { repo: 'edat-ims-github', status: 200 },
      { repo: 'edat-ims-github-spa', status: 200 },
      { repo: 'test-repo-one', status: 200 },
      { repo: 'test-repo-two', status: 200 },
      { repo: 'test-repo-three', status: 200 }
    ]
    
    filteredArr = obj2.filter(el1 => {
      return obj1.every(el2 => {
        return !(el1.repo == el2.repo && el1.status == el2.status)
      })
    })
    
    console.log(filteredArr)

    首先检查每个元素是否满足el1 不在el2 中。如果在el2中,那么every里面的return语句会返回一个false,这会导致函数中断并返回false。这意味着它已从过滤数组filteredArr 中删除。但是,如果它不在el2 中,那么every 语句返回true,这意味着它包含在filteredArr 中。

    【讨论】:

    • 这太完美了!谢谢。
    猜你喜欢
    • 2023-03-15
    • 2021-02-01
    • 2021-05-09
    • 1970-01-01
    • 2019-05-01
    • 2020-05-11
    • 2018-06-02
    • 2013-02-02
    • 2018-03-29
    相关资源
    最近更新 更多