Filtering highest value in array of strings

Hello,
I am new to Swift and just learning, so sorry if it looks easy, but I am stuck! :frowning:

lets say I have an array
let newArray = [ "first_01", "first_02",
"second_01", "second_02", "second_03",
"third",
"so_on"
]

I want to filter the array and output only the highest values of same items. In this case function should output only:
first_02, second_03

Whatever I do, I am stuck with different types and can't check. I was doing suffix(2), dropLast(2), later tried to do if and go through array but...
Please help to go through :slight_smile:

You need to be extremely specific about what you want to have happen.

Is it “If the string ends with an underscore followed by a nonzero number of base-ten digits, then treat those digits as an integer, and keep this entry only if the integer is greater than any other entry where the part before the underscore is identical; and if the string does not end that way then treat it as if it ended with underscore-zero.”?

This is my func:

func valuesWithNumbers() {
    
    let newArray = tricks.filter { (Substring) -> Bool in
        let numberRange = Substring.rangeOfCharacter(from: .decimalDigits)
        let hasNumber = (numberRange != nil)
        return hasNumber
    }
    
    for item in newArray {
        var newItem = item.dropLast(2)
        
        tricsDict.updateValue(item, forKey: .init())
        
        print(tricsDict)
    }

print(newArray)

}

as from the example, I can't use it properly. I was trying different ways to do that but unlucky..
In the func I was trying to do if item.suffix(2) is greater then another array value and item.dropLast(2) is the same as another in the value, but when I try to compare these items, I get an error and can't move on. So I need your help :slight_smile:

Do the tricks have to be stored as a string? Otherwise you could do something like this:

Create a data structure:

struct Trick: CustomStringConvertible {
    var name: String
    var number: Int
    
    var description: String { return "\(name) - \(number)" }
}

Map the array of tricks into a dictionary of the highest value tricks.

var allTricks: [Trick] = [
    Trick(name: "A", number: 1),
    Trick(name: "B", number: 1),
    Trick(name: "B", number: 2),
    Trick(name: "C", number: 1),
    Trick(name: "C", number: 3),
    Trick(name: "C", number: 5),
]

var result = allTricks.reduce(into: [String: Trick](), { output, trick in
    guard let existing = output[trick.name], 
        existing.number > trick.number else {
        output[trick.name] = trick
        return
    }
})

print(result) // [A - 1, B - 2, C - 5]