user6830957
user6830957

Reputation:

compare two array of objects and get difference

Mock

a = [{id:123},{id:1234},{id:12345}]
b = [{id:123},{id:1234},{id:123456}]

Code

a.filter((element)=> {
  return b.some((ele) =>{
    if (element.id === ele.id) {
     return matched[element.id] = element.id
    } else {
      return unmatched[element.id] = element.id
    }
 });
});

Expected output

matched = {123: 123, 1234: 1234}
unmatched = {12345: 12345}

output

unmatched = {123: 123, 1234: 1234, 12345: 12345}
matched = {123: 123, 1234: 1234}

could any one help me out here. I am trying to compare two arrays and get the difference into different objects

Upvotes: 1

Views: 100

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386604

You could take a Set or object for a and iterate b for getting the poperty into the right object.

const
    a = [{ id: 123 }, { id: 1234 }, { id: 12345 }],
    b = [{ id: 123 }, { id: 1234 }, { id: 123456 }],
    aSet = new Set(a.map(({ id }) => id)),
    [matched, unmatched] = b.reduce((r, { id }) => {
        Object.assign(r[1 - aSet.has(id)], { [id]: id });
        return r;
    }, [{}, {}]);
    

console.log(matched);
console.log(unmatched);
.as-console-wrapper { max-height: 100% !important; top: 0; }

An approach by using the objects directly

const
    a = [{ _id: '123', index: 3 }, { _id: '1234', index: 3 }],
    b = [{ _id: '123', index: 2 }, { _id: '12345', index: 3 }],
    aSet = new Set(a.map(({ _id }) => _id)),
    [matched, unmatched] = b.reduce((r, o) => {
        r[1 - aSet.has(o._id)].push(o);
        return r;
    }, [[], []]);
    
console.log(matched);
console.log(unmatched);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

Brother Woodrow
Brother Woodrow

Reputation: 6372

This would work:

a = [{id:123},{id:1234},{id:12345}];
b = [{id:123},{id:1234},{id:123456}];

function compare(a, b) {
    const returnObj = { matched: [], unmatched: [] };
    a.forEach(aItem => {
        const found = b.find(bItem => JSON.stringify(aItem) === JSON.stringify(bItem));
        returnObj[found ? 'matched' : 'unmatched'].push(aItem);
    });
    return returnObj;
}

const { matched, unmatched } = compare(a, b);

console.log(matched);
console.log(unmatched);

Upvotes: 0

Related Questions