The Cook The Cook - 3 months ago 11
iOS Question

How to remove common items from two struct arrays in Swift

In my app I have two struct arrays and I want to remove common items from one of them. My struct:

struct PeopleSelectItem {
var name = ""
var id = ""
var added = false
}


My arrays:

var people : [PeopleSelectItem] = []
var selectedPeople : [PeopleSelectItem] = []


I want to remove items from people array if they exist (compare by id) on selectedPeople array.

I tried several array filtering and converting to set but none of them worked. What can I do here?

Thanks!

Answer
  • Get an array of all ids in selectedPeople

    let selectedPeopleIDs = selectedPeople.map { $0.id }
    
  • Filter the items whose id is not in the array

    let filteredPeople = people.filter { !selectedPeopleIDs.contains($0.id) }
    
Comments