Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get key for value in map?

Tags:

elixir

Example:

map = %{a: 'apple', o: 'orange'}

Given the map above I want to get the key for the value 'orange'.

like image 354
user1167937 Avatar asked Dec 04 '22 00:12

user1167937


1 Answers

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".

like image 104
Gjaldon Avatar answered Dec 26 '22 22:12

Gjaldon