Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir: How to filter a Map by keys

Tags:

elixir

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.

like image 453
Ole Spaarmann Avatar asked Apr 18 '16 15:04

Ole Spaarmann


1 Answers

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}
like image 78
Dogbert Avatar answered Nov 16 '22 10:11

Dogbert