Search code examples
iosswiftsortingnsarrayalphanumeric

Sorting an NSArray of Objects by Letter then number


I have an array of "room" objects, each of these has a property called "room.descritpion" that is an NSString containing a mix of alphanumerical characters. These rooms need to be sorted in an array using the "room.description" property with ascending alphabetical order and then by number order ascending. I can get the alphabetical sorting done easily but I am struggling with how to incorporate the second sort which will be based on the number following the letter e.g. L21 L19 A34 A12 should be ordered in the array as A12, A34, L19, L21 and so on. The priority of the search should be letter first and then by number so a room with only numbers comes at the end of the array. The letters and numbers are not always in the same order i.e. the letter is not always first. I have read the documentation thoroughly but cannot seem to find the way to approach this. I am happy to use blocks if it makes the process easier. Any help would be greatly appreciated.


Solution

  • This

    var arr = ["A6", "A2", "3", "B4", "L8", "4", "B7"]
    let sortedArr = arr.sort({String($0) < String($1)})
    print(sortedArr)
    

    Will print out

    ["3", "4", "A2", "A6", "B4", "B7", "L8"]