Swift: Map Array of Objects Alphabetically by Name(String) into Separate Letter Collections within a new Array

let sortedContacts = contactData.sorted(by: { $0.name < $1.name }) // sort the Array first.
print(sortedContacts)

let groupedContacts = sortedContacts.reduce([[Contact]]()) {
    guard var last = $0.last else { return [[$1]] }
    var collection = $0
    if last.first!.name.characters.first == $1.name.characters.first {
        last += [$1]
        collection[collection.count - 1] = last
    } else {
        collection += [[$1]]
    }
    return collection
}
print(groupedContacts)
  1. sort the list. O(nlogn) , where n is the number of items in the Array(contactData).
  2. use reduce to iterate each contact in the list, then either add it to new group, or the last one. O(n), where n is the number of items in the Array(sortedContacts).

If you need to have a better printed information, you better make Contact conforms to protocol CustomStringConvertible

Tags:

Arrays

Ios

Swift