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

581 Views Asked by At

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)))
1

There are 1 best solutions below

0
On BEST ANSWER

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') ].
  • sorted: will return a sorted collection without changing the receiver
  • sort: will perform the sorting in-place and return itself

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' ))"