I am trying to sort the contents of the Array by alphabetical order by evaluating its first and third elements. I tried to use the 2nd and 3rd element in the array to evaluate and sort the array. But still I wasn't able to get the desired result.
Here's the content of the collection
#(#('Philippines' 'Davao' 'Durian')
#('Philippines' 'Cebu' 'Mango')
#('Philippines' 'Zambales' 'Lanzones)
#('Thailand' 'Bangkok' 'Durian')
#('Thailand' 'Phuket' 'Mango')
#('Vietnam' 'Ho chi min' 'Banana')
#('Vietnam' 'Hanoi' 'Mango'))
Here's what I did:
newArray := arrValues asArray.
newContent := newArray asSortedCollection: [ :ea :each | (ea at: 2) < (each at: 3) and: [ (ea at: 3) < (each at: 3) ] ].
Here's my output:
#(#('Vietnam' 'Ho chi min' 'Banana')
#('Thailand' 'Bangkok' 'Durian')
#('Philippines' 'Davao' 'Durian')
#('Vietnam' 'Hanoi' 'Mango'))
#('Thailand' 'Phuket' 'Mango')
#('Philippines' 'Zambales' 'Lanzones)
#('Philippines' 'Cebu' 'Mango')
The output should be:
#(#('Vietnam' 'Ho chi min' 'Banana')
#('Thailand' 'Bangkok' 'Durian')
#('Philippines' 'Davao' 'Durian')
#('Philippines' 'Cebu' 'Mango')
#('Vietnam' 'Hanoi' 'Mango'))
#('Thailand' 'Phuket' 'Mango')
#('Philippines' 'Zambales' 'Lanzones)
In Squeak and Pharo Smalltalk, you can write something like:
^arrValues sorted: #third ascending , #second ascending
or in Visualworks
^arrValues sorted:
[:subArray | subArray at: 3] ascending ,
[:subArray | subArray at: 2] ascending
We may thank Travis Griggs for introducing those nice SortFunction which give these good looking functional styles
He published this in his Objology blog http://objology.blogspot.com/2012/05/tag-memoizedfunctions.html and probably in earlier posts
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With