Jayesh
Jayesh

Reputation: 681

How to compare two objects and remove duplicate

I am trying to compare two objects and remove duplicate value from first one by splicing. is there any best solution to achieve this

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 = [];

Upvotes: 0

Views: 491

Answers (1)

Snow
Snow

Reputation: 4097

You're mutating Record1 while you're iterating over it with a for loop, starting at index 0 and incrementing upwards - this means that some items will be missed. (eg, if you break at a k of 0, then the new item at index 0 after splicing will never be checked.) Iterate from the end of Record1 instead, so that the k index that is spliced will always refer to the element at the proper index:

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

Or, even better, use a Set to reduce computational complexity and filter to create a new array:

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

Upvotes: 2

Related Questions