Created
April 13, 2016 13:16
-
-
Save pesterhazy/2b99f520f48ff2673c86e3b11f4480d2 to your computer and use it in GitHub Desktop.
Group a map by one or more keys
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn group-by-keys | |
"Group maps by a set of keys. For each key not grouped, all values are | |
returned as a set" | |
[ms kys] | |
(let [kys (set kys) | |
grouped (group-by #(select-keys % kys) ms)] | |
(map (fn [[pk pv]] | |
(into pk | |
(reduce (fn [a [k v]] (update a k #(conj (or % #{}) v))) | |
{} | |
(->> pv | |
(mapcat seq) | |
(remove (comp kys first)))))) | |
grouped))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment