KPO
KPO

Reputation: 37

Extracting the first character of names in a string array into another array

I am working with a string array that has about 1100 employee names.

I want to extract the first characters of the employee names so that i can divide the names in table view alphabetically and in different sections. Just like how the contacts app on iPhone does.

i tried this for extraction

var first_char = [String]()
while (i < employeenames.count)//employeenames is the names array 
    {
 first_char.append(String(employeenames[i].prefix(1)))
 i+=1
}

This way I am getting the desired characters but the code is taking really long. Also I want to count how many times "A" or "B" shows up in first_char array. Which is again taking another many seconds and smoking the CPU.

Please someone help me with this.

Upvotes: 0

Views: 577

Answers (3)

Sweeper
Sweeper

Reputation: 271865

You seem to want to do a "group by" operation on the array of names.

You want to group by the first character, so:

let groups = Dictionary(grouping: employeenames, by: { String($0.first!).uppercased() })

The return value will be [Character: [String]].

To count how many times A shows up, just do:

groups["A"].count

Upvotes: 2

Luca Angeletti
Luca Angeletti

Reputation: 59506

Given

let employee: [String] = ["James", "Tom", "Ben", "Jim"]

You can simply write

let firstCharacters = employee.compactMap { $0.first }

Result

print(firstCharacters)
["J", "T", "B", "J"]

Sorting

If you want the initial characters sorted you can add this line

let sortedFirstCharacters = firstCharacters.sorted()

["B", "J", "J", "T"]

Occurrencies

let occurrencies = NSCountedSet(array: firstCharacters)

let occurrenciesOfJ = occurrencies.count(for: Character("J"))
// 2

Upvotes: 0

Tom E
Tom E

Reputation: 1607

Use this code:

let employeenames = ["Peter", "John", "Frank"]
let firstChars = employeenames.map { String($0.first ?? Character("")) }

The order of the resulting single-character array will be the same as the order of the employeenames array. If you need sorting:

let sortedFirstChars = firstChars.sorted()

Upvotes: 1

Related Questions