CAIOHOBORGHI
Enum find by id?
How to find index of element inside enum by property?
I have this enum and I need to find the index of an item by its id(or another property).
[%{“code” => “ABEV3”, “comparison” => “>”, “field” => “close”, “id” => “4a9d96ce-e572-11eb-a557-0242ac170003”, “message” => “ABEV3 Close price is higher than 11.9!”, “value” => 11}]
How to do this?
Marked As Solved
Sebb
Sorry I most likely confused you with the hint that map-items are given as {k, v} to the function.
You have a list of maps, So you just do:
e = [%{foo: :bar, id: 1}, %{foo: :baz, id: 2}, %{foo: :foobar, id: 3}]
iex(3)> Enum.find_index(e, fn v -> v.id == 1 end)
0
So find_index goes through the list element by element, calls the function you provide and if this function return true, the index is returned.
Also Liked
Sebb
take a look at the great visual Elixir reference:
hauleth
Pinning, so it will match the already bound value instead of rebinding. However in this case I think that it would be more readable to do:
Enum.find(list, fn elem -> elem.id == id end)
entone
you can also use pattern matching
Enum.find_index(list, fn %{id: ^id} -> true; _ -> false end)
you could also use filter to just remove the item
Enum.filter(list, fn %{id: ^id} -> false; _ -> true end)
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









