Example:
map = %{a: 'apple', o: 'orange'}
Given the map above I want to get the key for the value 'orange'
.
To get the key of a specific value in a map, you could do the ff:
map
|> Enum.find(fn {key, val} -> val == 'orange' end)
|> elem(0)
The above returns :o
. Note that there's no function in standard lib that does this for us. This is likely because we are not meant to get the key based on the value in a map. It's always much more performant to get the value based on the key. Maybe you could rethink how you use the map and find a way to make 'orange'
the key.
By the way, you are using a char list for 'orange'
instead of a "string"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With