Best way to find which index in Enum.any? has satisfied its condition

Hi OGs,
Any ideas how to find the best way to find which index in Enum.any? has satisfied its condition ?

I have to iterate through a list and delete everything except one, I got fed with multiple lists and based on conditions, I would spare the last one in each list differently

The reason why I can’t iterate through a list and find the one I want to delete is due to the complexity of conditions, I need to know who they are, every single one of them in my list. For example, [%A{}, %B{}] I could just delete A as required, but [%A{} ,%B{} , %C{} , %D{}] I need to know C has what, D has what in order to delete A or else I have to delete C or D. That’s why I need to know which indexes are A, C, D through Enum.any?

Thank you

you’re looking for: Enum.find_index/2

1 Like

Enum.any?/2 returns truth if the function returns true for any of the elements. You could use Enum.find_index/2 in similar fashion, but i see that you need 3 indexes instead of 1.

Could you use something like this?

Enum.with_index(enumerable)
|> Enum.map(fn {value, index} ->
 {filter_function_result(value), index}
 end)
|> Enum.filter(fn {filter_value_result, index} -> filter_value_result == true)

This would return a list of tuples with the filter value result (booleans) and their indexes, so you can remove the results too if you want

1 Like

Expanding on @gpopides’s idea, you can get the value and the index of all elements that satisfy the condition with this:

enumerable
|> Enum.with_index()
|> Enum.filter( fn {value, index} -> filter_function(value) end )
1 Like