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

后端 未结 8 1909
孤独总比滥情好
孤独总比滥情好 2020-11-29 01:13

Any ideas what ???? should be? Is there a built in? What would be the best way to accomplish this task?

(def v [\"one\" \"two\" \"three\" \"two         


        
8条回答
  •  半阙折子戏
    2020-11-29 01:30

    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)
    

提交回复
热议问题