1

Hey i have array of objects, my goal is to split them into several arrays by common property value for example:

struct Person {
    let name: String
    let city: String
}

let persons: [Person] = [Person(name: "John", city: "San Francisco"),
                         Person(name: "Tim", city: "San Francisco"),
                         Person(name: "Bob", city: "Atlanta")]

my goal is to get arrays that contain only persons from same city. In that example result will be two arrays first contain John and Tim's objects, and 2nd contain only Bob's object.

Thanks

1 Answer 1

2

If I got you correctly, you should use a dictionary and group items by the city property:

let grouped = Dictionary(grouping: persons) { $0.city }

If you don't need the keys, then you can map them on values like:

let groupedWOKeys = grouped.map { $1 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.