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!

0

2 Answers 2

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"]]
Sign up to request clarification or add additional context in comments.

2 Comments

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
You can check out this answer for ways to split the string at whitespace.
1
Dictionary(grouping: names) { $0.split(separator: " ").last?.first } .values

Sort if necessary!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.