Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get difference between two array of object with different property comparer?

Tags:

javascript

I have these two arrays:

main:

[
   { id: "1"},
   { id: "2"},
   { id: "3"}
]

filtered:

[
   { id: "80", link_id: "1"},
   { id: "50", link_id: null},
   { id: "67", link_id: "3"}
]

I need to get the items of main which have as id those contained in filtered with the property: link_id, I tried with:

main.filter(x => filtered.includes(x.id));

the problem is that this will return null, and also this doesn't allow me to check if link_id is null

var main = [{
      id: "1"
    },
    {
      id: "2"
    },
    {
      id: "3"
    }
  ],
  filtered = [{
      id: "80",
      link_id: "1"
    },
    {
      id: "50",
      link_id: null
    },
    {
      id: "67",
      link_id: "3"
    }
  ],
  result = main.filter(x =>
    filtered.includes(x.id)
  );

console.log(result)
like image 648
sfarzoso Avatar asked Jan 22 '19 15:01

sfarzoso


People also ask

How will you differentiate between arrays and objects in JavaScript?

Both objects and arrays are considered “special” in JavaScript. Objects represent a special data type that is mutable and can be used to store a collection of data (rather than just a single value). Arrays are a special type of variable that is also mutable and can also be used to store a list of values.

How do I compare two array values in TypeScript?

To get the difference between two arrays in TypeScript: Use the filter() method to iterate over the first array. Check if each element is not contained in the second array. Repeat the steps, but this time iterate over the second array.


1 Answers

Try with some() method

var main = [
   { id: "1"},
   { id: "2"},
   { id: "3"}
]


var filtered = [
   { id: "80", link_id: "1"},
   { id: "50", link_id: null},
   { id: "67", link_id: "3"}
]


console.log(main.filter(x => filtered.some(item => item.link_id === x.id) ));
like image 154
Deep Avatar answered Sep 28 '22 14:09

Deep