【发布时间】:2020-06-29 16:25:19
【问题描述】:
我有一组对象,我试图根据某些属性(第一个和最后一个)查找重复项。我的逻辑似乎是错误的,这是我尝试过的。
我的最终结果应该类似于:
[
{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));
【问题讨论】:
-
请不要使用
.map进行简单的迭代。当您要将数组转换为另一个数组时使用它。如果您只需要遍历这些值,请使用.forEach()或普通循环。 -
感谢@VLAZ 我更新了
标签: javascript arrays duplicates