samir samir - 4 months ago 10
Swift Question

Compare and filter custom objects in an array

I want to filter an array of objects.

struct Person {
let name: String
}

let p1 = Person(name:"test1")
let p2 = Person(name:"test1")
let p3 = Person(name:"test2")

let persons = [p1, p2, p3]


How i can filter the
persons
list and return the persons which have the same name?

I have tried to use a filter method, but I can't apply it with multiple arguments.

I am looking for a functional solution like a
filter
or a
reduce
function and not looping over the list.

Answer

Since you are looking for a groupBy functionality here's my solution

let personsByName = persons.reduce([String:[Person]]()) { (res, person) -> [String:[Person]] in
    var res = res
    res[person.name] = (res[person.name] ?? []) + [person]
    return res
}

Now personsByName is a dictionary where the key is the name of the person and the values are all the Person struct with that name

["test2": [Person(name: "test2")], "test1": [Person(name: "test1"), Person(name: "test1")]]

If you want the result as [[Person]]

let personsLists = Array(
        persons.reduce([String:[Person]]()) { (res, person) -> [String:[Person]] in
            var res = res
            res[person.name] = (res[person.name] ?? []) + [person]
            return res
         }
     .values)

[[Person(name: "test2")], [Person(name: "test1"), Person(name: "test1")]]]

Comments