I have a Map with key-value pairs and a Tuple with atoms. I want to remove any entry from the Map where the key is not an atom in the Tuple
m = %{value1: nil, value2: nil, value4: nil}
t = {:value1, :value3, :value4}
# The result should be %{value1: nil, value4: nil}
It is kind of an intersect problem. I looked into Enum.filter
and MapSet
but didn't find an elegant solution. This must be a common problem and your input is highly appreciated.
Use Map.take/2
and a Tuple.to_list/1
:
iex(1)> m = %{value1: nil, value2: nil, value4: nil}
%{value1: nil, value2: nil, value4: nil}
iex(2)> t = {:value1, :value3, :value4}
{:value1, :value3, :value4}
iex(3)> Map.take(m, Tuple.to_list(t))
%{value1: nil, value4: nil}
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