[英]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 .首先,请不要在不执行映射操作时使用.map()
。 I've substituted the usage of .map
with .forEach
as the latter is more appropriate in this case.我用.forEach
代替了.map
的用法,因为后者在这种情况下更合适。
Second, your comment //probably need to remove something here
is correct - you do have to remove an item.其次,您的评论//probably need to remove something here
是正确的 - 您必须删除一个项目。 Namely, you have to remove the duplicate item rec
that was just found.也就是说,您必须删除刚刚找到的重复项rec
。 To do that, you can utilise Array#splice
which requires the index to be removed.为此,您可以使用需要删除索引的Array#splice
。 You can easily get the index as the second parameter of the .forEach()
callback您可以轻松获取索引作为.forEach()
回调的第二个参数
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.