I have a list of maps that I want to reduce since it often includes name-duplicates, but I can't just use Enum.uniq because I want to add up the count-column, for example:
list = [%{count: 4, name: "first"}, %{count: 43, name: "second"},
%{count: 11, name: "third"}, %{count: 11, name: "first"},
%{count: 11, name: "second"}, %{count: 28, name: "second"}]
the result I after is this:
[%{count: 15, name: "first"}, %{count: 82, name: "second"}, %{count: 11, name: "third"}]
After finding this tread: How to map and reduce List of Maps in Elixir
I come up with something like this;
all_maps
|> Enum.group_by(&(&1.name))
|> Enum.map(fn {key, value} ->
%{name: key, count: value |> Enum.reduce(fn(x, acc) -> x.count + acc.count end)}
end)
but it's only working when there is multiple with the same name, the list above would give this result:
[%{count: 15, name: "first"}, %{count: 82, name: "second"}, %{count: %{count: 11, name: "third"}, name: "third"}]
and sometimes it's only one so I need something that works in both cases, any tips?