findfirst

findfirst(predicate, A)

Return the index of the first element of A for which predicate returns true.

Examples

  1. Find the index of the first occurrence:

    julia> arr = [5, 10, 15, 20, 10, 25];
    julia> findfirst(arr, 10)
    2

    This example returns the index of the first occurrence of the value 10 in the array arr.

  2. Search for a string in an array of strings:

    julia> words = ["apple", "banana", "orange", "apple"];
    julia> findfirst(words, "apple")
    1

    It finds the index of the first occurrence of the string "apple" in the array of strings.

  3. Handle cases when the element is not found:
    julia> numbers = [1, 2, 3, 4];
    julia> findfirst(numbers, 5)
    nothing

    It returns nothing when the element is not found in the collection.

Common mistake example:

julia> arr = [5, 10, 15, 20];
julia> findfirst(arr, 25)
ERROR: MethodError: no method matching findfirst(::Array{Int64,1}, ::Int64)

In this example, the element 25 does not exist in the array arr. It is important to ensure that the element being searched for exists in the collection to avoid such errors.

See Also

find, findfirst, findin, findlast, findmin, findn, findnext, findnz, findprev, rsearch, rsearchindex, searchsorted, searchsortedfirst, searchsortedlast, sort, sort!, sortcols, sortperm, sortperm!,

User Contributed Notes

Add a Note

The format of note supported is markdown, use triple backtick to start and end a code block.

*Required Field
Details

Checking you are not a robot: