简体   繁体   中英

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. 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 .

 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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