Reputation: 1
I need to find the max value in [[String:Any]]
array which looks like :
"date":someDate
"value":8
.
.
"date":anotherDate
"value":13
.
I need the max value(13), is there a simple way without the traditional looping over the array and extracting all numbers etc ?
Upvotes: 4
Views: 1081
Reputation: 318854
Here's one possible solution using Array max(by:)
.
Note that this example uses a lot of crash operators (!
). Safely unwrap as needed for your real code:
let data: [[String: Any]] = [
["date":Date(), "value":8],
["date":Data(), "value":13],
]
let maxEntry = data.max { ($0["value"] as! Int) < ($1["value"] as! Int) }!
let maxValue = maxEntry["value"] as! Int
Another option is to use map
and max
:
let maxValue = data.map { $0["value"] as! Int }.max()!
All these examples assume the array won't be empty and that each dictionary has a valid Int
value for the "value"
key. Adjust the code as needed if these assumptions are not valid.
Upvotes: 6