Created
April 14, 2022 15:05
-
-
Save xhh/d5dea45feeb798ac5e6277e340bebb72 to your computer and use it in GitHub Desktop.
groups maps by common keys
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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