leontalbot
leontalbot

Reputation: 2543

Distributing and merging hash-map elements in Clojure

What would be quickest way to transform this collection :

[[{:a 1} {:a 2} {:a 3}] [{:b 4} {:b 5} {:b 6}] [{:c 7} {:c 8} {:c 9}]]

into this collection? :

[{:a 1, :b 4, :c 7} {:a 2, :b 5, :c 8} {:a 3, :b 6, :c 9}]

I've come up with this but I still feel it could be shorter :

(map (partial apply merge) 
     (apply map vector collection))

Note that the numbers are randomly picked, just to show that the content of each val is unique...

Upvotes: 1

Views: 118

Answers (1)

A. Webb
A. Webb

Reputation: 26446

(def data [[{:a 1} {:a 2} {:a 3}] [{:b 4} {:b 5} {:b 6}] [{:c 7} {:c 8} {:c 9}]])

(apply mapv merge data)
;=> [{:a 1, :c 7, :b 4} {:a 2, :c 8, :b 5} {:a 3, :c 9, :b 6}]

Upvotes: 5

Related Questions