Question

I have the following map:

MyVals {12 -3, 24 -9, 36 -777, 48 -3037, 180 0, 360 0, 240 0, 120 0, 0 0, 144 0, 3 0, 6 -1, 9 -1, 108 0, 60 0, 72 0, 84 0, 96 0}

I am removing zero values then I need to sort it by the key

MyValsZeroRemoved(apply merge (for [[k v] MyVals :when (not (= 0 v))] {k v}))

Which returns:

MyValsZeroRemoved {9 -1, 6 -1, 48 -3037, 36 -777, 24 -9, 12 -3}

Then I sort it:

MyValsZeroRemovedSorted(sort MyValsZeroRemoved)

but that results in

([12 -3] [24 -9] [36 -777] [48 -3037] [6 -1] [9 -1])

How do I sort the map to get the desired output as below:

([6 -1] [9 -1] [12 -3] [24 -9] [36 -777] [48 -3037])
Was it helpful?

Solution

The only way you get that sort order is if you did

(sort-by (comp str first) {9 7, 6 5, 3 3, 0 -1, 36 4670, 24 3203, 12 23})
;=>  ([0 -1] [12 23] [24 3203] [3 3] [36 4670] [6 5] [9 7])

That will sort them as strings. If you need to sort a map by key literals then regular sort works

(sort {9 7, 6 5, 3 3, 0 -1, 36 4670, 24 3203, 12 23})
;=>  ([0 -1] [3 3] [6 5] [9 7] [12 23] [24 3203] [36 4670])

If you need to sort by the value or if you need to convert the key or value then you should use sort-by and a function to extract the value to perform the conversion.

(sort-by second {9 7, 6 5, 3 3, 0 -1, 36 4670, 24 3203, 12 23})
;=>  ([0 -1] [3 3] [6 5] [9 7] [12 23] [24 3203] [36 4670])

OTHER TIPS

The sort function will give the output you want.

user> (sort {9 7, 6 5, 3 3, 0 -1, 36 4670, 24 3203, 12 23})
([0 -1] [3 3] [6 5] [9 7] [12 23] [24 3203] [36 4670])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top