Finding indices of max value in swift array

What you need is to use custom class or structure and make array of it then find max score and after that filter your array with max score.

struct Player {
    let name: String
    let score: Int
}

Now create array of this Player structure

var players = [Player(name: "Bill", score: 10), Player(name: "Bob", score: 15), Player(name: "Sam", score: 12), Player(name: "Dave", score: 15)]

let maxScore = players.max(by: { $0.0.score < $0.1.score })?.score ?? 0

To get the array of player with max core use filter on array like this.

let allPlayerWithMaxScore = players.filter { $0.score == maxScore }

To get the array of index for player having high score use filter on array like this.

let indexForPlayerWithMaxScore = players.indices.filter { players[$0].score == maxScore }
print(indexForPlayerWithMaxScore) //[1, 3]

The accepted answer doesn't generalize to comparing computed values on the elements. The simplest and most efficient way to get the min/max value and index is to enumerate the list and work with the tuples (offset, element) instead:

struct Player {
    let name: String
    let stats: [Double]
}

let found = players.enumerated().max(by: { (a, b) in
   battingAvg(a.element.stats) < battingAvg(b.element.stats)
})

print(found.element.name, found.offset)  // "Joe", 42

In general you shouldn't rely on comparing floating point values by equality and even where you can, if the computation is expensive you don't want to repeat it to find the item in the list.

Tags:

Arrays

Swift