Reputation: 3630
I have a vector of maps. I want to associate an index element for each element.
Example:
(append-index [{:name "foo"} {:name "bar"} {:name "baz"}])
should return
[{:name "foo" :index 1} {:name "bar" :index 2} {:name "baz" :index 3}]
What is the best way to implement append-index function?
Upvotes: 3
Views: 929
Reputation: 17859
just adding some fun:
(defn append-index [items]
(map assoc items (repeat :index) (range)))
Upvotes: 1
Reputation: 51470
First of all, Clojure starts counting vector elements from 0, so you probably want to get
[{:index 0, :name "foo"} {:index 1, :name "bar"} {:index 2, :name "baz"}]
You could do it pretty easily with map-indexed
function
(defn append-index [coll]
(map-indexed #(assoc %2 :index %1) coll))
Upvotes: 7