Davide Scheriani
Davide Scheriani

Reputation: 45

Swift create new arrays based on a single array from a property

I'm rater new to Swift and I'm stuck in a piece of code where I have to convert a single dimensional array of items, to a new multidimensional array but grouping the items checking for a similarity of a variable.

Like this:

var arr1 = [("polly", 23, uk), ("polly", 19, canada), ("polly", 29, us), ("jenny", 78, ireland), ("jenny", 78, ireland)....]

then, grouping all the items by the same name, I wish to have this:

arrA = (do some code and return this) [("polly", 23, uk), ("polly", 19, canada), ("polly", 29, us)]
arrB = (do some code and return this) [("jenny", 78, ireland), ("jenny", 78, ireland)]

arrFinal = [arrA, arrB]

Basically, I have a list of items to split in each group in a tableview, each section need to show the items that have the same property, and the user choose from a menu, which property use (name, age or enumerator) to group all the items per each section.

Thanks!

Upvotes: 1

Views: 605

Answers (1)

matt
matt

Reputation: 535925

Once you do some prep work, this is essentially a one-liner. Here's the prep (my assumptions are a little different from yours):

enum Country {
    case uk
    case canada
    case us
    case ireland
}
struct Person {
    let name : String
    let age : Int
    let country : Country
}
let arr = [
    Person(name: "polly", age: 23, country: .uk),
    Person(name: "polly", age: 19, country: .canada),
    Person(name: "polly", age: 29, country: .us),
    Person(name: "jenny", age: 78, country: .ireland),
    Person(name: "jenny", age: 78, country: .ireland),
]

And here's the actual code:

let arr2 = Array(Dictionary.init(grouping: arr) {$0.name}.values)

To group by, say, age instead of name, change $0.name to $0.age.

Upvotes: 3

Related Questions