What is an elegant way of finding matches between properties of two arrays of structures?

I’ve seen various answers online about finding matches between two arrays including the use of intersect and filter, but these solutions don’t seem possible when dealing with structures and their properties.

struct Example {var name: String}

var arr1 = [Example(name: "Sam"), Example(name: "Ash"), Example(name: "Mike")]
var arr2 = [Example(name: "David"), Example(name: "Sam"), Example(name: "Leonard")]

Without using a bunch of "for loops", I want to remove Sam from arr1 if it has a match in arr2. Is there an elegant way of doing this?

>Solution :

You can first put all the names in arr2 in a set, and then use removeAll to remove from arr1. In removeAll, you can specify a condition, and this is where you query the set to see if the Example in arr1 has a name that matches one of those in arr2.

let namesToExclude = Set(arr2.map(\.name))
arr1.removeAll { namesToExclude.contains($0.name) }

Leave a Reply