根据属性值删除对象数组中的重复项

时间:2020-03-18 14:44:03

标签: javascript arrays duplicates

我有一个对象数组,我试图根据某些属性(第一个和最后一个)查找重复项。我的逻辑似乎不正确,这就是我尝试过的。

我的最终结果应类似于:

[
  {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));

1 个答案:

答案 0 :(得分:1)

首先,请don't use .map() when not performing a mapping operation。我已将.map的使用替换为.forEach,因为在这种情况下后者更合适。

第二,您的评论//probably need to remove something here是正确的-您必须删除一个项目。即,您必须删除刚刚找到的重复项rec。为此,您可以利用Array#splice来删除索引。您可以轻松获取索引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));

相关问题