I'm hoping to find a cljs equivalent of Underscore's "indexBy" http://underscorejs.org/#indexBy . Would anyone be able to point me in the right direction?
group-by
?
given a list of json objects, if I group by a key (say: id), the value will be a list correct?
group-by
returns a map.
and the values are lists, correct.
technically a vector.
ideally I would have (group-by :id items) => {:1 {:title "title here" :description "description here"} :2 {:title "another title" ....}
Maybe something like this then?
(into {} (map (juxt :age identity) [{:name "moe" :age 40} {:name "larry" :age 50} {:name "curly" :age 60}]))
juxt
is a too clever way of saying "make me a vector of results of applying those functions to something"
that works perfectly! I'll have to look into juxt
now
juxt ftw
(that is in this case it is equivalent to (fn [map] [(:age map) (identity map)])
)
(map (juxt inc dec) [1 2 3]) ;; ([2 0] [3 1] [4 2])
That's clever. I need to use juxt
more often.
source: https://github.com/clojure/clojure/blob/clojure-1.7.0/src/clj/clojure/core.clj#L2445
That said, depending on how you use it later, you could just use group-by
and just destructure on that, for example:
(for [[id [val & _]] (group-by :age [{:name "moe" :age 40} {:name "larry" :age 50} {:name "curly" :age 60}])]
(println "id=" id "; val=" val))
So you won't have to write your own function then
looks like clojuredocs beat us to it http://clojuredocs.org/clojure.core/juxt#example-542692cfc026201cdc326e12
I noticed that but it's slightly different than the data structure that underscore returns
Swear I didn't see that before ; d
{:key {:map "map"}}
vs {:key [{:map1 "map1"}]}
Does it? The first is indexBy
, the second is groupBy
.
Yep, you're right jaen. There is a groupBy that returns the same thing.