Skip to content

Instantly share code, notes, and snippets.

@xhh
Created April 14, 2022 15:05
Show Gist options
  • Save xhh/d5dea45feeb798ac5e6277e340bebb72 to your computer and use it in GitHub Desktop.
Save xhh/d5dea45feeb798ac5e6277e340bebb72 to your computer and use it in GitHub Desktop.
groups maps by common keys
list = [
%{id: 1, k: "k1", name: "name a", text: "text a"},
%{id: 1, k: "k1", name: "name b", other: "other b"},
%{id: 1, k: "k2", name: "name k2", other: "other k2"}
]
keys = [:id, :k]
list
|> Enum.group_by(&Map.take(&1, keys))
|> Enum.map(fn {common, others} ->
others
|> Enum.reduce(%{}, fn data, acc ->
Enum.reduce(data, acc, fn {k, v}, acc ->
case acc do
%{^k => vs} -> %{acc | k => [v | vs]}
acc -> Map.put(acc, k, [v])
end
end)
end)
|> Map.merge(common)
end)
_output = """
[
%{id: 1, k: "k1", name: ["name b", "name a"], other: ["other b"], text: ["text a"]},
%{id: 1, k: "k2", name: ["name k2"], other: ["other k2"]}
]
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment