user14860979
user14860979

Reputation: 127

Filtering an array of objects with another array

Array1 = [{id: "1"}.{id: 2},{id: "3"}]


Array2 = [{id: "1"}.{id: 2},{id: "3"}, {id: "4"}, {id: "5"}]

I need to get the objects from Array 2 that no are in array 1;

The result should be:

ArrayFiltered = [{id: "4"}, {id: "5"}]

So how can I do that with typescript?

Upvotes: 0

Views: 36

Answers (1)

Cody E
Cody E

Reputation: 189

There is no built in function to find this, so you need to build one.

The answer @Roberto provides is probably the best you are going to get...

Array2.filter(elem2 => !Array1.some(elem1 => elem1.id === elem2.id)

Here are some links

Filter: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

Some: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

If the filter conditional is more complex in your use case, I recommend pulling the callback out and titling it in a separate function so you can call it like this

Array2.filter(el => disjointFilter(Array1, el))

Upvotes: 1

Related Questions