简体   繁体   English

如何比较两个对象数组并删除 JavaScript 中的重复项?

[英]How to compare two arrays of objects and remove duplicates in JavaScript?

In the below code when removing an object from a checklist array its removing the last two, but if I change the object order and move the last two objects to the first two places then it is working fine.在下面的代码中,当从checklist数组中删除一个对象时,它删除了最后两个,但是如果我更改对象顺序并将最后两个对象移动到前两个位置,那么它工作正常。 Why?为什么? Is there any better solution to remove duplicates from an array of objects?有没有更好的解决方案来从对象数组中删除重复项?

const checklist = [
  { id: 1, value: "Elenor Anderson", isSelected: false },
  { id: 2, value: "Caden Kunze", isSelected: false },
  { id: 110, value: "Ms. Hortense Zulauf", isSelected: false },
  { id: 112, value: "Grady Reichert", isSelected: false }
];

const mainlist = [
  { id: 36, value: "Ms. Hortense Zulauf", isSelected: false },
  { id: 46, value: "Grady Reichert", isSelected: false },
  { id: 1, value: "Elenor Anderson", isSelected: false },
  { id: 2, value: "Caden Kunze", isSelected: false }
];

checklist.forEach(item => {
  var ItemIndex = mainlist.findIndex(b => b.id === item.id);
  console.log(ItemIndex);
  checklist.splice(ItemIndex, 1);
});

console.log(this.checklist);

You can use Array.prototype.filter .您可以使用Array.prototype.filter

 const checklist = [ {id:1,value:'Elenor Anderson',isSelected:false}, {id:2,value:'Caden Kunze',isSelected:false}, {id:110,value:'Ms. Hortense Zulauf',isSelected:false}, {id:112,value:'Grady Reichert',isSelected:false}, ]; const mainlist = [ {id:36,value:'Ms. Hortense Zulauf',isSelected:false}, {id:46,value:'Grady Reichert',isSelected:false}, {id:1,value:'Elenor Anderson',isSelected:false}, {id:2,value:'Caden Kunze',isSelected:false} ]; const ids = mainlist.map(e => e.id); let filtered = checklist.filter(e => ids.includes(e.id)); console.log(filtered)

Or can create a Set for O(n) complexity.或者可以为 O(n) 复杂性创建一个Set

const ids =new Set(mainlist.map(e => e.id));
let filtered = checklist.filter(e => ids.has(e.id));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM