我有一个包含重复对象的数组,我想删除那些重复的对象。但我似乎无法找到合适的解决方案。我这里的错误是什么?
对象如下。
{name: "login", text: "Login"}
{name: "navigation", text: "Navigation"}
{name: "landing", text: "Landing Page"}
{name: "login", text: "Login"}
{name: "navigation", text: "Navigation"}
{name: "landing", text: "Landing Page"}
以下是我的代码,其中 items
包含对象数组。
this.subMenuItems = this.items.reduce((acc, current) => {
const x = acc.find(item => item.name === current.name);
if (!x) {
return acc.concat([current]);
} else {
return acc;
}
}, []);
答案 0 :(得分:3)
这将分配 this.subMenuItems
一个只包含每个项目的第一个实例的数组,因为 indexOf
返回找到对象的第一个索引。
this.subMenuItems = this.items.filter((item, index, self) => self.indexOf(item) === index);
答案 1 :(得分:0)
您的代码的问题在于 find
将始终返回定义的值,因为至少有一个对象满足条件(current
对象本身)
一个解决方案是@Issac 给出的解决方案。它的时间和空间复杂度分别为 O(n^2)
和 O(1)
。
还有一种时间和空间复杂度分别为 O(n)
和 O(n)
的解决方案。
function removeDuplicates(objects) {
const map = new Map()
for (const obj of objects) {
map.put(obj.name, obj)
}
return map.values()
}
答案 2 :(得分:-1)
else