Efficient way to filter a Map by value in Elixir

后端 未结 4 877
情深已故
情深已故 2021-01-04 14:20

In Elixir, what would be an efficient way to filter a Map by its values.

Right now I have the following solution

%{foo: \"bar\", biz: ni         


        
4条回答
  •  心在旅途
    2021-01-04 15:00

    You can also write like this:

    m = %{foo: "bar", biz: nil, baz: 4}
    
    Enum.reduce(m, m, fn 
      {key, nil}, acc -> Map.delete(acc, key)
      {_, _}, acc -> acc
    end)
    

    The code above is quite efficient if there are few nil values in m.

提交回复
热议问题