Search code examples
clojure

Sort nested map Clojure


I am trying to sort a map by a key value. Given this map:

{:1 {:bar "something" :rank 10} :2 {:bar "other" :rank 20}}

I like to sort it by rank value:

{:2 {:bar "other" :rank 20} :1 {:bar "something" :rank 10} }

Its possible using sort-by ?

Thanks in advance


Solution

  • sort-by takes a key function as well as an optional custom comparator

    ;              keyfn         comparator
    (sort-by (comp :rank second) > 
      {:1 {:bar "something" :rank 10} :2 {:bar "other" :rank 20}})
    ;=> ([:2 {:bar "other", :rank 20}] [:1 {:bar "something", :rank 10}])