0

I have two object arrays and want to find the items that are missing in the second array but are part of the first array,basically array1-array2.I tried to use filter but I'm unable to get the desired result.Please help.Thanks in advance.

Here is the code:

 testData=[
       {id: 0, name: "policy001"},
       {id: 2, name: "policy002"}];
       sourceData= [
          {id: 0, name: "policy001"},
          {id: 2, name: "policy002"},
          {id: 3, name: "policy003"},
          {id: 4, name: "policy004"},
          {id: 5, name: "policy005"}, 
      ];

      let missing = sourceData.filter(item =>  testData.indexOf(item) < 0);
      console.log("Miss")
      console.log(missing )//Returns the sourceData instead of diff.
wentjun
  • 40,384
  • 10
  • 95
  • 107
rock11
  • 718
  • 4
  • 17
  • 34
  • 1
    Possible duplicate of [How to get the difference between two arrays of objects in JavaScript](https://stackoverflow.com/questions/21987909/how-to-get-the-difference-between-two-arrays-of-objects-in-javascript) – wentjun May 10 '19 at 06:37

3 Answers3

1

The reason your code did not work is that object inside array are "addresses" to the objects. So of course the indexOf did not work

try below:

let missing = sourceData.filter(a => !testData.find(b => a.id === b.id));
Qiaosen Huang
  • 1,093
  • 1
  • 10
  • 25
1

Try findIndex():

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating that no element passed the test.

testData = [{
        id: 0,
        name: "policy001"
    },
    {
        id: 2,
        name: "policy002"
    }
];
sourceData = [{
        id: 0,
        name: "policy001"
    },
    {
        id: 2,
        name: "policy002"
    },
    {
        id: 3,
        name: "policy003"
    },
    {
        id: 4,
        name: "policy004"
    },
    {
        id: 5,
        name: "policy005"
    },
];

console.log(sourceData.filter(item => testData.findIndex(x => x.id == item.id) < 0))
Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
1

You're getting this undesired behavior because what you're doing in your filter is comparing the items' references rather than their values. if you want to compare that those objects are actually identical in values (because they have different references), you need to do the following:

let missing = sourceData.filter(sourceItem => 
  testData.every(testItem =>
    testItem.id !== sourceItem.id && testItem.name !== sourceItem.name
  )
)

this means - filter out those element of sourceData, for which none of the elements in testData has the same id or name. They are "missing".

Smytt
  • 364
  • 1
  • 11