5

Suppose I have this vector of maps:

[{:title "Title1" :id 18347125}
 {:title "Title2" :id 18347123}
 {:title "Title3" :id 18341121}]

And I wish to select the map with :id 18347125, how would I do this?

I've tried

(for [map maps
      :when (= (:id map) id)]
    map)

This feels a bit ugly and returns a sequence of length one, and I want to return just the map.

4 Answers 4

11

IMHO, there are several ways to solve your problem, and the definitely idiomatic way is in the realm of taste. This is my solution where I simply translated "to select maps whose :id is 1834715" into Clojure.

user> (def xs [{:title "Title1" :id 18347125}
               {:title "Title2" :id 18347123}
               {:title "Title3" :id 18341121}])
#'user/xs

user> (filter (comp #{18347125} :id) xs)
({:title "Title1", :id 18347125})

The :id keyword is a function that looks up itself in a collection passed to it. The set #{18347125} is also a function that tests if a value passed to it equals 18347125. Using a Clojure set as a predicate function allows for a succinct idiom.

4

I'm not sure if it's the simplest way to write it, but I think this is more clear about your intentions:

(->> maps
     (filter #(= (:id %) id))
     first)
1
  • All good answers but I'm accepting this as it directly solves my problem.
    – Pete
    May 21, 2015 at 10:23
3

This doesn't do what you asked for exactly, but might be useful nonetheless:

user=> (group-by :id [{:title "Title1" :id 18347125}
                      {:title "Title2" :id 18347123}
                      {:title "Title3" :id 18341121}])
{18347125 [{:title "Title1" :id 18347125}]
 18347123 [{:title "Title2" :id 18347123}]
 18341121 [{:title "Title3" :id 18341121}]}

Now you can simply look the map up by id. Read more about group-by on clojuredocs, its a very useful function.

Note that it puts the maps inside vectors. This is because group-by is designed to handle grouping (ie multiple items with the same key):

user=> (group-by :id [{:title "Title1" :id 123}
                      {:title "Title2" :id 123}
                      {:title "Title3" :id 18341121}])
{123 [{:title "Title1" :id 123} {:title "Title2" :id 123}]
 18341121 [{:title "Title3" :id 18341121}]}
0

If you need to query not just once, but multiple times for maps with specific IDs, I would suggest to make your data types match your use case, i.e. to change the vector into a map:

(def maps-by-id (zipmap (map :id maps) maps))

So now your IDs are the keys in this new map of maps:

user=> (maps-by-id 18347125)
{:title "Title1", :id 18347125}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.