Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a dictionary by an array value contained in the dictionary Swift

I have a dictionary that contains arrays as its elements and I want to sort by one of the array values. All the solutions I found for sorting dictionaries where for single elements and not arrays. Also, I didn't understand what $0.0 meant? Below is a code example of what I'm trying to accomplish.

var dict = ["Mike": [62, 160], "Jim": [72, 210], "Tony": [68, 187]]

//I want to sort by the height (array values [0]) from highest value to lowest.
//The output would look like this:

"Jim": [72, 210]
"Tony": [68,187]
"Mike": [62,160]

I'm relatively new to coding so I really have no idea how to approach this.

like image 309
abuessing Avatar asked Nov 19 '25 09:11

abuessing


1 Answers

See, you have dictionary to be sorted:

let dict = ["Mike": [62, 160], "Jim": [72, 210], "Tony": [68, 187]]

You want to sort it with some function isOrderedBefore: (Self.Generator.Element, Self.Generator.Element) -> Bool so if the first one element should have been higher than the second one, you should put a > b into the function and so on.

let sortedDict = dict.sort { (first: (String, Array<Int>), second: (String, Array<Int>)) -> Bool in
    return first.1[0] > second.1[0]
}

It's the same as:

let sortedDict = dict.sort {
    return $0.1[0] > $1.1[0]
}

Or:

let sortedDict = dict.sort { $0.1[0] > $1.1[0] }

$0 means that your function's variable has number 0 and so on. $0.0 means that you got the first dictionary field (in your case it's a name), while $0.1 means it's the second dictionary field (an array).

like image 51
Beraliv Avatar answered Nov 21 '25 23:11

Beraliv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!