1

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' } ]

Dürrani
  • 950
  • 12
  • 21

2 Answers2

1
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' } ]
Dürrani
  • 950
  • 12
  • 21
  • 2
    This works. But consider replacing the inner `.filter` with `.some`, which feels more natural than using a `filter` and comparing length to 0. Eg: `return !secondList.some(second => second.key === first.key)`. – CRice Sep 23 '20 at 11:46
0

You could take a Set for the second array and filter the first array for excluding elements with same key of the second array.

const
    firstList = [{ key: "aa" }, { key: "bb" }, { key: "cc" }],
    secondList = [{ key: "dd" }, { key: "cc" }],
    keys = new Set(secondList.map(({ key }) => key)),
    result = firstList.filter(({ key }) => !keys.has(key));

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392