0

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.

KPO
  • 37
  • 1
  • 7
  • I made something similar in Objective-C https://stackoverflow.com/questions/45675849/get-sectionindex-titles-based-on-contact-name/45772425#45772425 You can get some ideas... – Larme Jul 25 '18 at 12:50
  • Strongly related: https://stackoverflow.com/questions/31220002/how-to-group-by-the-elements-of-an-array-in-swift. – Martin R Jul 25 '18 at 13:02

3 Answers3

2

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
Sweeper
  • 213,210
  • 22
  • 193
  • 313
1

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()
Tom E
  • 1,530
  • 9
  • 17
0

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
Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148