简体   繁体   中英

Removing Duplicates in Array of Objects based on Property Values

I have an array of objects I am trying to find duplicates based on some properties (first and last). My logic appears to be off and here is what I have tried.

My final result should look similar to:

[
  {first:"John", last: "Smith", id:"1234", dupes: [555,666]},
  {first:"John", last: "Jones", id:"333", dupes: []}
];

 let arrayOfObjects = [ {first:"John", last: "Smith", id:"1234", dupes: []}, {first:"John", last: "Smith", id:"555", dupes: []}, {first:"John", last: "Jones", id:"333", dupes: []}, {first:"John", last: "Smith", id:"666", dupes: []} ]; arrayOfObjects.forEach(record => { arrayOfObjects.forEach(rec => { if(record.first == rec.first && record.last == rec.last && record.id !== rec.id){ console.log("match found for: " + JSON.stringify(record) + " and: " + JSON.stringify(rec)); record.dupes.push(rec.id); //probably need to remove something here } }); }); console.log(JSON.stringify(arrayOfObjects));

First off, please don't use .map() when not performing a mapping operation . I've substituted the usage of .map with .forEach as the latter is more appropriate in this case.

Second, your comment //probably need to remove something here is correct - you do have to remove an item. Namely, you have to remove the duplicate item rec that was just found. To do that, you can utilise Array#splice which requires the index to be removed. You can easily get the index as the second parameter of the .forEach() callback

 let arrayOfObjects = [ {first:"John", last: "Smith", id:"1234", dupes: []}, {first:"John", last: "Smith", id:"555", dupes: []}, {first:"John", last: "Jones", id:"333", dupes: []}, {first:"John", last: "Smith", id:"666", dupes: []} ]; arrayOfObjects.forEach(record => { arrayOfObjects.forEach((rec, index) => { // get index ------------------^^^^^-->------------------>--------------v if(record.first == rec.first && // | record.last == rec.last && // | record.id !== rec.id){ // | record.dupes.push(rec.id); // | arrayOfObjects.splice(index, 1) //<--- remove using the index --< } }); }); console.log(JSON.stringify(arrayOfObjects));

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