Fork me on GitHub
#beginners
<
2015-11-08
>
charliegriefer20:11:59

Quick question (I think). I have a collection of maps. Each map will contain the same 2 keys, but different values. I’d like to merge those maps by one key and group the other key’s values into a vector.

charliegriefer20:11:40

I’m sure there must be some elegant way using merge or merge-with or something similar to accomplish this, but I’m hitting a wall.

charliegriefer20:11:49

({:id 1, :title "Star Wars"} {:id 1, :title "Indiana Jones"} {:id 1, :title "E.T."} {:id 2, :title "Rocky”})

charliegriefer20:11:01

({:id 1, :title ["Star Wars" "Indiana Jones" "E.T."]} {:id 2, :title ["Rocky"]})

akiva20:11:39

That might be what you’re after.

charliegriefer20:11:20

oooh! That definitely gets me much closer!

charliegriefer20:11:41

i should be able to finish it from there

charliegriefer20:11:03

i knew there was likely something built in and elegant. I was going to write a huge function and map it over the collection simple_smile

charliegriefer21:11:42

this ended up getting me the result I was looking for

charliegriefer21:11:46

(->> '({:id 1 :title "Star Wars"} {:id 1 :title "Indiana Jones"} {:id 1 :title "E.T."} {:id 2 :title "Rocky"})
           (group-by :id)
           (map (fn [[k v]] {:id k :titles (mapv :title v)})))