3

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!

galmeriol
  • 461
  • 4
  • 14
Hans
  • 287
  • 1
  • 5
  • 18

2 Answers2

4

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;
 })
})
Fateh Mohamed
  • 20,445
  • 5
  • 43
  • 52
1
    using filter you can remove duplicate by compare tow array object in loop and filter return result array 

    this.array2.forEach((item2) => {

     this.array1 = this.array1.filter((item1) => {
       //use JSON.stringify() to compare tow objects
       return JSON.stringify(item1) !== JSON.stringify(item2);
     })

    })
    console.log(this.array1);
mittal bhatt
  • 955
  • 6
  • 13
  • Please add more detail to your answer. Why does this work? What was the issue that you resolved? That makes it easier for OP and everyone in the future to understand their problem. – Terru_theTerror May 30 '18 at 10:05