Search code examples
clojureclojurescript

How to get first element map from an array using clojure


I have an array of result ({:a one}). I want a result which returns one when I select or give :a.

I used vals,get-in functions but since the map is inside a list they are not working. Can you please help me how do I do that.

I need to return value for a given key.

Also,

What if the data is of the form

({:a “Favorite fruit", :measurements [{:a “fav game?", :b "x",
:name “foot ball", :max 7.0, :min 0.0, :id “12345"}], :name “Frequency”})

and I want to select :a "fav game?" :name "foot ball" and :min 0.0 ?

Thank you


Solution

  • List comprehension

    List comprehension using for with any quantity of elements in the list:

    (for [x data :let [m (:measurements x)]] (map #(let [{:keys [a name min]} %] [a name min]) m))
    

    Details:

    • for [x data for every element in data
    • :let [m (:measurements x)]] set m as a symbol for :measurements
    • (map #(let [{:keys [a name min]} %] [a name min]) m) for every m get the keys a name min and output a vector [a name min].

    Output:

    ((["fav name?" "foot ball" 0.0]))
    

    Or one result

    Directly using apply:

    (let [{:keys [a name min]} (apply (comp first :measurements) data)] [a name min])
    

    Details:

    • (apply (comp first :measurements) data) apply composition, first get :measurements then the first elem.
    • let [{:keys [a name min]} get the keys a name min from the map and output a vector [a name min].

    Output:

    ["fav name?" "foot ball" 0.0]