0

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);
Kate Orlova
  • 3,225
  • 5
  • 11
  • 35

1 Answers1

0

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));
AZ_
  • 3,094
  • 1
  • 9
  • 19