All posts

Get the index position from element in a matched condition

 elixir

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:

Postscript:

I built two products to help fund continued efforts for this website, it would mean a lot if you would check them out:
1. 2500+ Words for the Undermotivated Software Engineer - A short essay I wrote on the titled topic ($3).
2. Build 3 Chrome Extensions in Under 2 Hours - A course I built to teach chrome extension development ($9-20).