如何从角度为 6 的数组中删除重复的对象

SRA*_*NSV 7 typescript angular2-services angular angular5 angular6

我正在尝试删除数组中的重复值对象但不起作用...我认为重复函数正在运行但未反映在li列表中。你能找出我必须改变的地方吗?

我的服务文件:

 addComp(Names,c){   
 this.item.push({ name: Names, componentid: c});
 this.uniqueArray = this.removeDuplicates(this.item, "name"); //this line issue
 this.item=this.uniqueArray; //this line issue
 }
Run Code Online (Sandbox Code Playgroud)

Dev*_*tel 15

const result = Array.from(this.item.reduce((m, t) => m.set(t.name, t), new Map()).values());
Run Code Online (Sandbox Code Playgroud)

这可能会解决您的问题。


小智 7

this.item = this.item.filter((el, i, a) => i === a.indexOf(el))
Run Code Online (Sandbox Code Playgroud)


Ian*_*ald 5

如果addComp是您修改的唯一地方this.item,只需在插入前检查是否存在。重复项永远不会放入数组中,因此您永远不必修剪它们。

addComp(Names,c){
  let item = {name: Names, componentid: c};
  if (this.item.find((test) => test.name === Names) === undefined) {
    this.item.push(item);
  }
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您正在修改其他地方this.item,您应该在更预期的地方去除重复项。将它们作为addComp函数的副作用剥离是出乎意料的。不过,你可以这样做...

addComp(Names,c){
  this.item.push({name: Names, componentid: c});
  this.item = this.item.filter((test, index, array) =>
     index === array.findIndex((findTest) =>
        findTest.name === test.name
     )
  );
}
Run Code Online (Sandbox Code Playgroud)