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

标签 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));

最佳答案

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

其次,您的评论//可能需要在此处删除某些内容是正确的 - 您确实必须删除一个项目。也就是说,您必须删除刚刚找到的重复项 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));

关于javascript - 根据属性值删除对象数组中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60741865/

相关文章:

java - 如何从 Hashmap 中删除重复的键

Javascript 和媒体查询

javascript - Midnight Commander 可以识别光标键的什么代码?

Python查找重复项: Find out if there are duplicate numbers and the index diff is at most k

python - 搜索多个目录,删除重复文件

c - 传递指针数组并接收错误消息

javascript - 单击 div 时更改图像

javascript - 如何使用 ASP.Net 中的 PageMethods 将多维数组从 Javascript 传递到服务器

java - 确定 Set S 中是否存在两个元素之和正好为 x - 正确解?

javascript - lodash _.includes 的 Vanilla Javascript 等价物