Given the following list in Clojure:
(def pairs '[(2,1),(3,2),(2,4)])
I want to merge these based overlapping first item in the pair, and select the one with the greater second value.
ie I want them to merge into:
[(3,2),(2,4)]
because (2,1)
and (2,4)
have matching first values, and (2,4)
has the greater second value, so it bumps off (2,1)
.
My question is: How do I merge pairs based on a nested value?
This is what I attempted:
(reduce
(fn [first-pair second-pair]
(if (not (= (first first-pair) (first second-pair)))
(conj first-pair second-pair)
(if (> (second first-pair) (second second-pair))
first-pair
second-pair)))
pairs
)