Efficient way to filter a Map by value in Elixir

后端 未结 4 846
情深已故
情深已故 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:07

    It could be a little expensive but it is more declarative, which IMO adds more value. Also consider how big is going to be your collection and if it makes sense to optimize this filter.

    However, I understand your concern, so here is what I did:

    %{foo: "bar", biz: nil, baz: 4}
    |> Enum.reduce(%{}, filter_nil_values/2)
    

    Where filter_nil_values/2 is defined as

    defp filter_nil_values({_k, nil}, accum), do: accum
    defp filter_nil_values({k, v}, accum), do: Map.put(accum, k, v)
    

    I tried to do this in a one-line function, but it looks awful.

提交回复
热议问题