Fork me on GitHub
#admin-announcements
<
2015-11-24
>
naderhen18:11:48

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?

naderhen18:11:37

given a list of json objects, if I group by a key (say: id), the value will be a list correct?

jstew18:11:53

group-by returns a map.

jstew18:11:07

and the values are lists, correct.

jstew18:11:32

technically a vector.

naderhen18:11:08

ideally I would have (group-by :id items) => {:1 {:title "title here" :description "description here"} :2 {:title "another title" ....}

jaen18:11:29

Maybe something like this then?

(into {} (map (juxt :age identity) [{:name "moe" :age 40} {:name "larry" :age 50} {:name "curly" :age 60}]))

jaen18:11:04

juxt is a too clever way of saying "make me a vector of results of applying those functions to something"

naderhen18:11:18

that works perfectly! I'll have to look into juxt now

jaen18:11:51

(that is in this case it is equivalent to (fn [map] [(:age map) (identity map)]))

robert-stuttaford18:11:09

(map (juxt inc dec) [1 2 3]) ;; ([2 0] [3 1] [4 2])

jstew18:11:46

That's clever. I need to use juxt more often.

jaen18:11:37

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))

jaen18:11:43

So you won't have to write your own function then

jstew19:11:21

I noticed that but it's slightly different than the data structure that underscore returns

jaen19:11:40

Swear I didn't see that before ; d

jstew19:11:25

{:key {:map "map"}} vs {:key [{:map1 "map1"}]}

jaen19:11:11

Does it? The first is indexBy, the second is groupBy.

jstew19:11:44

Yep, you're right jaen. There is a groupBy that returns the same thing.