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.
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).
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])])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With