1

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)))
eMBee
  • 793
  • 6
  • 16
ludo
  • 543
  • 3
  • 14
  • 3
    Just use a sort block. For example, to sort in ascending order of the valu e for `'age'`: `anArrayOfDictionarys sort: [ :a :b | (a at: 'age') < (b at: 'age') ].` The Pharo/Smalltalk documentation is your friend and first line of defense in knowing these things. :) – lurker Jan 19 '18 at 14:18
  • @lurker can you link me to docs describing sort:/sorted:? because I don't recall it ever seeing in any Pharo book. – Peter Uhnak Jan 19 '18 at 15:15
  • @Peter well.... I apologize, I guess I spoke too soon. I knew Pharo ordered collections accepted the `sort:` message, but evidently the docs are not up to date. – lurker Jan 19 '18 at 16:32
  • ludo, It seems @Peter answered your question spot on. Is there anything missing that prevents you from accepting his answer? – lurker Jan 20 '18 at 17:18
  • yes indeed lurker It seems like what I need @Peter. Thank you. – ludo Jan 21 '18 at 12:14

1 Answers1

6

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' ))"
Peter Uhnak
  • 9,617
  • 5
  • 38
  • 51