6

Lets say I have an array of values (in alphabetical order) such as [A, B, B, B, D, G, G, H, M, M, M, M, Z] representing the last names of users. I am looking to create a table index, so what is the best way to separate an array like this (any number of users with last names that start with all letters of the alphabet) into arrays such as [A] [B, B, B] [D] [G, G] [H] [M, M, M, M] [Z] This seems to be the best way to create values for a table with multiple sections where users are separated by last name. Thanks for any help!

Baylor Mitchell
  • 1,029
  • 1
  • 11
  • 19

2 Answers2

12

You can use name.characters.first to get a name's initial, and build up an array of arrays by comparing them:

let names = ["Aaron", "Alice", "Bob", "Charlie", "Chelsea", "David"]

var result: [[String]] = []
var prevInitial: Character? = nil
for name in names {
    let initial = name.characters.first
    if initial != prevInitial {  // We're starting a new letter
        result.append([])
        prevInitial = initial
    }
    result[result.endIndex - 1].append(name)
}

print(result)  // [["Aaron", "Alice"], ["Bob"], ["Charlie", "Chelsea"], ["David"]]
jtbandes
  • 115,675
  • 35
  • 233
  • 266
  • Thank you very much. How could I Modify the line `let initial = name.characters.first` so that it will detect the character after a space (for the last name)? i.e. I want it sorted by the `D` in `John Doe` – Baylor Mitchell Apr 18 '16 at 01:38
  • You can check out [this answer](http://stackoverflow.com/questions/25678373/swift-split-a-string-into-an-array) for ways to split the string at whitespace. – jtbandes Apr 18 '16 at 01:40
1
Dictionary(grouping: names) { $0.split(separator: " ").last?.first } .values

Sort if necessary!