user3083633
user3083633

Reputation: 91

reodering keys in maps inside a list of maps

I have a function which outputs a list of maps which look something like this:

({:size20160721 "19.94 GB", :size20160720 "19.94 GB", :size20160719 "100 GB", :directory_path "/user/1 "}
 {:size20160721 "1 GB", :size20160720 "4 GB", :size20160719 "10 GB", :directory_path "/user/2 "}
 ...
 )

how can I reorder this list of maps so that each map has :directory_path first, followed by :size keys the number of which which can be variable but will be the same for all paths?

Upvotes: 2

Views: 65

Answers (1)

leetwinski
leetwinski

Reputation: 17859

use sorted-map-by, with comparator which would always set:directory_path on the first place:

user> 
(def data '({:size20160721 "19.94 GB", :size20160720 "19.94 GB",
             :size20160719 "100 GB", :directory_path "/user/1 "}
            {:size20160721 "1 GB", :size20160720 "4 GB",
             :size20160719 "10 GB", :directory_path "/user/2 "}))
;; #'user/data

user> 
(def dirfirst (sorted-map-by #(cond (= :directory_path %1) -1
                                    (= :directory_path %2) 1
                                    :else (compare %1 %2))))
;; #'user/dirfirst

user> (map (partial into dirfirst) data)

;; ({:directory_path "/user/1 ", :size20160719 "100 GB", 
;;   :size20160720 "19.94 GB", :size20160721 "19.94 GB"}
;;  {:directory_path "/user/2 ", :size20160719 "10 GB", 
;;   :size20160720 "4 GB", :size20160721 "1 GB"})

Upvotes: 2

Related Questions