Angular5 compare 2 array of (JSON) objects and splice when found match

Hans picture Hans · May 30, 2018 · Viewed 7.5k times · Source

If i have 2 arrays with (JSON) objects and i want to compare them and splice an object when there is a match what is the best way to do this.

Example:

Array 1:

[{test: 1, test2: 2}, {test: 3, test2: 5}, {test: 6, test2: 8}]

Array 2:

[{test: 6, test2: 8}, {test: 1, test2: 2}]

Now we see that Array 1 index 0 and Array 2 index 1 are a match. What I want to do now is splice the object from array 1.

Is there a good/smart way to achieve this?

thx!

Answer

Fateh Mohamed picture Fateh Mohamed · May 30, 2018

try this, using filter, filter will loop over array1 and return an array of elements that match the condition (element that doesn't exist in array2)

array2.foreach((element) => {
 array1 = array1.filter((element1) => {
   return element1 !== element;
 })
})