JavaScript - 对象数组 - 比较和删除重复项 ES6



我有两个对象:

对象一

[
{ 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多个对象。

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

谢谢:(

试试这个代码:

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。这意味着它被从滤波后的阵列CCD_ 6中移除。但是,如果它不在el2中,则every语句返回true,这意味着它包含在filteredArr中。

最新更新