DVNold
DVNold

Reputation: 929

Finding the index of an item in a Vector in Julia

If I have a Vector of Strings such as: ["big", "friendly", "giant"], how can I get the index of "friendly" (2)?

Upvotes: 4

Views: 8535

Answers (1)

htl
htl

Reputation: 459

You can use the findfirst function (and its friends findlast, findnext, findprev and findall) for problems like this.

julia> x = ["big", "friendly", "giant"]
julia> findfirst(item -> item == "friendly", x)
2

This uses an anonymous function item -> item == "friendly" which tests each item in the array. If the function returns true the index of that item is returned. You can write it slightly more concisely as

julia> findfirst(==("friendly"), x)
2

If the item isn't found, nothing is returned.

Upvotes: 10

Related Questions