Skip to content

Instantly share code, notes, and snippets.

@pesterhazy
Created April 13, 2016 13:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pesterhazy/2b99f520f48ff2673c86e3b11f4480d2 to your computer and use it in GitHub Desktop.
Save pesterhazy/2b99f520f48ff2673c86e3b11f4480d2 to your computer and use it in GitHub Desktop.
Group a map by one or more keys
(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