user6099709 user6099709 - 1 year ago 67
Swift Question

Swift: How to split an array of Strings into multiple arrays of matching value?

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!

Answer Source

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
        prevInitial = initial
    result[result.endIndex - 1].append(name)

print(result)  // [["Aaron", "Alice"], ["Bob"], ["Charlie", "Chelsea"], ["David"]]