Search code examples
clojure

Reducing a list of maps to a list by in clojure


I've started to get some functional programming some weeks ago and I'm trying to perform a mapping from a list of maps to a list considering a specific key in clojure.

My list of maps looks like: '({:a "a1" :b "b1" :c "c1"} {:a "a2" :b "b2" :c "c2"} {:a "a3" :b "b3" :c "c3"})

And the output I'm trying to get is: '("b1" "b2" "b3").

I've tried the following:

(doseq [m maps]
  (println (list (get m :b))))

And my output is a list of lists (what is expected as I'm creating a list for each iteration). So my question is, how can I reduce this to a single list?

Update

Just tried the following:

(let [x '()]
  (doseq [m map]
    (conj x (get m :b))))

However, it is still not working. I`m not getting the point as I was expecting to be appending the elements into a empty list


Solution

  • This is a very common pattern in production Clojure code so it's a good place to learn. In general check out the docs on sequences at https://clojure.org/reference/sequences and when faced with similar task, look to see which pattern best fits and explore functions in that group. In this case it's "Process each item of a seq to create a new seq" and the first item listed is map

    your example might look like

     (map :b my-data)