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

Answer

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