Search code examples
javascriptnode.jstypescriptarraylistdifference

Difference (upon custom attributes) between two arrays having partial similar objects i.e a-b


How to find difference between two JavaScript arrays having partial similar objects?

Diff = A minus B

const firstList = [{ key: "aa", name:"a" }, { key: "bb", name:"b" }, { key: "cc", name:"c" }];
const secondList = [{ key: "dd", id: 1 }, { key: "cc", id: 2 }];

I want something like const diff = firstList - secondList;

In this case diff needs to hold [ { key: 'aa', name: 'a' }, { key: 'bb', name: 'b' } ]


Solution

  • const firstList = [{ key: "aa", name:"a" }, { key: "bb", name:"b" }, { key: "cc", name:"c" }];
    const secondList = [{ key: "dd", id: 1 }, { key: "cc", id: 2 }];
    
    const diff = firstList.filter((first) => {
      return !secondList.some((second) => second.key === first.key);
    });
    
    diff; // [ { key: 'aa', name: 'a' }, { key: 'bb', name: 'b' } ]