Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get index for an item in reagent

When I iterate over vector in Reagent, like this:

(for [item ["rattata" "pidgey" "spearow"]]
  [:li item])])

I would like to get index of a specific item - like this:

  [:li item index]

I'm not asking about general clojure 'for', because another way to iterate over vector will satisfy me as well.

like image 933
Oskar Skuteli Avatar asked Dec 25 '22 03:12

Oskar Skuteli


2 Answers

This is actually a general Clojure question, rather than specific to Reagent, but there are a few way you could do this.

You can approach it similarly to your current code with something like

(def items ["rattata" "pidgey" "spearow"])
(for [index (range (count items))]
  [:li (get items index) index])

You could also use map-indexed

(doall (map-indexed (fn [index item] [:li index item]) items))

The doall in this case is for Reagent, as map and friends return lazy lists that can interfere with Reagent (it will print a warning to the console if you forget it).

like image 194
Walton Hoops Avatar answered Dec 31 '22 13:12

Walton Hoops


You can also combine map-indexed with for-loop:

(for [[index item] (map-indexed vector items)]
  [:li item index])])

; vector function is a shorthand:
(for [[index item] (map-indexed (fn [index item] [index item]) items)]
  [:li item index])])
like image 35
Simon Perepelitsa Avatar answered Dec 31 '22 13:12

Simon Perepelitsa