How do I find the index of an item in a vector?

Built-in:

user> (def v ["one" "two" "three" "two"])
#'user/v
user> (.indexOf v "two")
1
user> (.indexOf v "foo")
-1

If you want a lazy seq of the indices for all matches:

user> (map-indexed vector v)
([0 "one"] [1 "two"] [2 "three"] [3 "two"])
user> (filter #(= "two" (second %)) *1)
([1 "two"] [3 "two"])
user> (map first *1)
(1 3)
user> (map first 
           (filter #(= (second %) "two")
                   (map-indexed vector v)))
(1 3)

(defn find-thing [needle haystack]
  (keep-indexed #(when (= %2 needle) %1) haystack))

But I'd like to warn you against fiddling with indices: most often than not it's going to produce less idiomatic, awkward Clojure.


Stuart Halloway has given a really nice answer in this post http://www.mail-archive.com/[email protected]/msg34159.html.

(use '[clojure.contrib.seq :only (positions)])
(def v ["one" "two" "three" "two"])
(positions #{"two"} v) ; -> (1 3)

If you wish to grab the first value just use first on the result.

(first (positions #{"two"} v)) ; -> 1

EDIT: Because clojure.contrib.seq has vanished I updated my answer with an example of a simple implementation:

(defn positions
  [pred coll]
  (keep-indexed (fn [idx x]
                  (when (pred x)
                    idx))
                coll))

Tags:

Clojure