如何比较两个对象并删除重复项

How to compare two objects and remove duplicate

我正在尝试比较两个对象并通过拼接从第一个对象中删除重复值。有没有最好的解决方案来实现这个

Record1 = [{"ID":"938"},{"ID":"939"}];

Record2 = [{"IDN":"938"},{"IDN":"939"}];

for (var k = 0; k < Record1.length; k++) {
    for (var l = 0; l < Record2.length; l++) {
        if (Record1[k].ID == Record2[l].IDN) {
            Record1.splice(k, 1);
            break;
        }
    }
}

console.log(''+ JSON.stringify(Record1));

Actual result> Record1 = [{"ID":"939"}];

Expected result> Record1 = [];

您在使用 for 循环迭代它时改变 Record1,从索引 0 开始并向上递增 - 这意味着将遗漏一些项目。 (例如,如果您 breakk 为 0,则永远不会检查拼接后索引 0 处的 new 项目。)从 end of Record1 代替,这样拼接的 k 索引将始终引用正确索引处的元素:

Record1 = [{"ID":"938"},{"ID":"939"}];

Record2 = [{"IDN":"938"},{"IDN":"939"}];

for (var k = Record1.length - 1; k >= 0; k--) {
    for (var l = 0; l < Record2.length; l++) {
        if (Record1[k].ID == Record2[l].IDN) {
            Record1.splice(k, 1);
            break;
        }
    }
}

console.log(''+ JSON.stringify(Record1));

或者,更好的是,使用 Set 来降低计算复杂度并使用 filter 创建新数组:

Record1 = [{"ID":"938"},{"ID":"939"}];
Record2 = [{"IDN":"938"},{"IDN":"939"}];

const IDNs = new Set(Record2.map(({ IDN }) => IDN));
const Record1WithoutDupes = Record1.filter(({ ID }) => !IDNs.has(ID));
console.log(Record1WithoutDupes);