smalltalkpharopharo-5

How can we sort dictionaries in an array by a specific key in pharo?


I have an array containing several dictionaries. How can I sorted them using a key that each dictionary have like age?

an Array((a Dictionary('age'->'20' 'ID'->1254))(a Dictionary('age'->'35' 'ID'->1350))(a Dictionary('age'->'42' 'ID'->1425)))

Solution

  • You can sort by providing a comparator block; the block takes two arguments (two elements from the array) and is expected to return boolean.

    data := { 
        { 'age' -> '20'. 'ID' -> 1254 } asDictionary.
        { 'age' -> '35'. 'ID' -> 1350 } asDictionary.
        { 'age' -> '42'. 'ID' -> 1425 } asDictionary
    }.
    sorted := data sorted: [ :a :b | (a at: 'age') > (b at: 'age') ].
    

    You can also use asSortedCollection: which will create a new collection that always upholds the sorting invariant.

    sc := data asSortedCollection: [ :a :b | (a at: 'age') > (b at: 'age') ].
    
    "automatically inserted between age 42 and 35"
    sc add: {'age' -> '39'. 'ID' -> 1500} asDictionary.
    sc "a SortedCollection(a Dictionary('ID'->1425 'age'->'42' ) a Dictionary('ID'->1500 'age'->'39' ) a Dictionary('ID'->1350 'age'->'35' ) a Dictionary('ID'->1254 'age'->'20' ))"