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!

Baylor Mitchell
  • 989
  • 1
  • 10
  • 18

4 Answers4

13

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"]]
jtbandes
  • 110,948
  • 34
  • 232
  • 256
  • 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` – Baylor Mitchell Apr 18 '16 at 01:38
  • You can check out [this answer](http://stackoverflow.com/questions/25678373/swift-split-a-string-into-an-array) for ways to split the string at whitespace. – jtbandes Apr 18 '16 at 01:40
0

I think nice way to do this is using filter. Try this code :

var array = ["Aa", "Ab", "Bb", "Cc","d", "DDD"]

let A_array = array.filter({
    ($0.characters.first == "A" || $0.characters.first == "a" )
})

Hope it help you

kamwysoc
  • 6,607
  • 1
  • 33
  • 48
0
Dictionary(grouping: names) { $0.split(separator: " ").last?.first } .values

Sort if necessary!

Jessy
  • 10,211
  • 5
  • 28
  • 41
-2

You'll need to loop through your original array and rebuild it into a new one. Here's an example:

$names = array ('anthony', 'bernie', 'bob', 'hank', 'mary', 'mike', 'steve', 'tom', 'tony');
$new_names = array();

foreach ($names as $name) {
  //get first letter of name
  $firstletter = substr($name, 0,1);

  //test if there is already an array for this letter
  //if not, create it
  if (!$new_names[$firstletter]) {
      $new_names[$firstletter] = array();
  }

  //add the name to the new array under the correct first letter
  array_push($new_names[$firstletter], $name);
}