Get the index position from element in a matched condition
To achieve the desired outcome of the post title, you can use the Enum
modules find_index/2
function. This function will accept two arguments, the enumberable itself and a callback function as parameters. If the callback function finds a matched condition it will return that items index position. If there are more than two of the same item it will return the first matches index position. If there are no matches found, it will return nil
.
Enum.find_index(["football", "baseball", "hockey", "basketball"], fn sport -> sport == "hockey" end)
=> 2
Enum.find_index(["football", "baseball", "hockey", "hockey"], fn sport -> sport == "hockey" end)
=> 2
Enum.find_index(["football", "baseball", "hockey", "hockey"], fn sport -> sport == "soccer" end)
=> nil
Further reading: