3

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?

4
  • Show us what you've tried so far. Commented Dec 28, 2015 at 9:43
  • I just want the position in the vector as index. I think I actually found a function that will do what I want so I'll just answer this myself and close this. Commented Dec 28, 2015 at 9:44
  • Side note: if you think about it, it doesn't make much sense to add the index on the map. You can add it when you fetch it. Be lazy my friend. Commented Dec 28, 2015 at 9:45
  • This is part of a larger thing that involves fetching recursive structure from database via external library and then sorting it (at html/javascript side). Commented Dec 28, 2015 at 9:49

2 Answers 2

7

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))
Sign up to request clarification or add additional context in comments.

Comments

1

just adding some fun:

(defn append-index [items]
  (map assoc items (repeat :index) (range)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.