m-arv
m-arv

Reputation: 463

Clojure: filter list of maps by 2nd list

Got a list of maps like

({:a "a" :b "b" :c "c"}
 {:a "d" :b "e" :c "f"}
 {:a "g" :b "h" :c "i"}
 {:a "j" :b "k" :c "l"})

and a 2nd list like ("c" "i").

I need to filter the list of maps by the 2nd lists entries for a result like as

({:a "a" :b "b" :c "c"} {:a "g" :b "h" :c "i"})

but dont get a clue how.

Upvotes: 0

Views: 95

Answers (1)

Thumbnail
Thumbnail

Reputation: 13483

Given

(def data
   (list
     {:a "a" :b "b" :c "c"}
     {:a "d" :b "e" :c "f"}
     {:a "g" :b "h" :c "i"}
     {:a "j" :b "k" :c "l"}))

Then

=> (filter (comp (set (list "c" "i")) :c) data)
({:a "a", :b "b", :c "c"} {:a "g", :b "h", :c "i"})
  • Your lists need list as the operator (or to be quoted).
  • I assume you want to filter by the value for key :c, which need not be the second entry in the printed map.

You need to get to grips with two or three aspects of Clojure:

  • How sequence functions like filter work.
  • Using sets and keywords as functions.
  • What comp does.

Upvotes: 3

Related Questions