0

So I have the following problem. I have two arrays of objects. Array1 contains many objects and Array2 contains a part of these objects:

array1: [{"first_name": "Wanda", 
          "id": 27, 
          "last_name": "Walhai"}, 
       
         {"first_name": "Victoria", 
          "id": 26, 
          "last_name": "Viperfisch"}]

array2: [{"first_name": "Victoria", 
          "id": 26, 
          "last_name": "Viperfisch"}]

And what I want to do is to delete all objects in array1 that array2 contains too (the duplicates). So the new array1 should look like this:

array1: [{"first_name": "Wanda", 
          "id": 27, 
          "last_name": "Walhai"}]

Can anybody help me to achieve this in javascript? Thanks a lot.

Tönner
  • 3
  • 1

1 Answers1

1

You can use a Set for all your identifiers and use it to filter out ids that show up on the other array.

function filterById(mainArr, filterArr){
     let idSet = new Set(filterArr.map(obj => obj.id));
     return mainArr.filter(obj => !idSet.has(obj.id));
}

This will remove all objects in mainArr with a specific id that show up in filterArr.

Example here:

let arr = [{
    "first_name": "Wanda",
    "id": 27,
    "last_name": "Walhai"
  },

  {
    "first_name": "Victoria",
    "id": 26,
    "last_name": "Viperfisch"
  }
]

let filterArr = [{
  "first_name": "Victoria",
  "id": 26,
  "last_name": "Viperfisch"
}]

function filterById(mainArr, filterArr){
     let idSet = new Set(filterArr.map(obj => obj.id));
     return mainArr.filter(obj => !idSet.has(obj.id));
}

console.log(filterById(arr, filterArr));
MinusFour
  • 13,913
  • 3
  • 30
  • 39