Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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) }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading