Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 330
Baylor Mitchell Avatar asked Apr 17 '16 21:04

Baylor Mitchell


1 Answers

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"]]
like image 184
jtbandes Avatar answered Oct 13 '22 00:10

jtbandes