I am working on a list that happens to have such items
[
%{localtions: [], doctors: [%{name: "Junaid", hospital: "west"}, %{name: "Farooq", hospital: "test"}]},
%{localtions: [%{name: "Dom", address: "test"}, %{name: "Domi", address: "west"}], doctors: []},
%{localtions: [], doctors: []},
%{localtions: [%{name: "Dominic", address: "test"}, %{name: "DomDom", address: "west"}], doctors: []}
]
I am trying to convert it into this only.
[locations: [%{name: "Domi", address: "test"}, %{name: "Dom", address: "test"}%{name: "Dominic", address: "test"}, %{name: "DomDom", address: "west"}], doctors: [%{name: "Junaid", hospital: "west"}, %{name: "Farooq", hospital: "test"}]]
any help would be great, thank you.
You can use this functions based on your need:
t = [
%{
localtions: [],
doctors: [%{name: "Junaid", hospital: "west"}, %{name: "Farooq", hospital: "test"}]
},
%{
localtions: [%{name: "Dom", address: "test"}, %{name: "Dom", address: "west"}],
doctors: []
},
%{localtions: [], doctors: []},
%{
localtions: [%{name: "Dominic", address: "test"}, %{name: "DomDom", address: "west"}],
doctors: []
}
]
the function is defined as:
def name_is_unique(l) do
Enum.reduce(l, %{}, fn x, mp ->
Map.merge(mp, x, fn _k, v1, v2 ->
Enum.reduce(v1 ++ v2, %{}, fn x, acc -> Map.put(acc, x.name, x) end)
|> Map.values()
end)
end)
end
def duplication_check(l) do # with duplication check
Enum.reduce(l, %{}, fn x, mp ->
Map.merge(mp, x, fn _k1, mpV1, mpV2 ->
(mpV1 ++ mpV2) # [%{name: "Dom"}, %{name: "Dom"}]
|> Enum.reduce(MapSet.new(), fn inerListMap, inerMapSet ->
MapSet.put(inerMapSet, inerListMap) # %{name: "Dom"}
end)
|> MapSet.to_list()
end)
end)
end
def with_duplication(l) do
Enum.reduce(l, %{}, fn x, mp ->
Map.merge(mp, x, fn _k1, mpV1, mpV2 ->
mpV1 ++ mpV2
end)
end)
end
if your uniqueness is the name key then use name_is_unique or if you want full uniqueness over map items use duplication_check and don't care about duplication use with_duplication
name_is_unique(t)
%{
doctors: [
%{hospital: "test", name: "Farooq"},
%{hospital: "west", name: "Junaid"}
],
localtions: [
%{address: "west", name: "Dom"},
%{address: "west", name: "DomDom"},
%{address: "test", name: "Dominic"}
]
}
duplication_check(t)
%{
doctors: [
%{hospital: "test", name: "Farooq"},
%{hospital: "west", name: "Junaid"}
],
localtions: [
%{address: "test", name: "Dom"},
%{address: "test", name: "Dominic"},
%{address: "west", name: "Dom"},
%{address: "west", name: "DomDom"}
]
}
with_duplication(t)
%{
doctors: [
%{hospital: "west", name: "Junaid"},
%{hospital: "test", name: "Farooq"}
],
localtions: [
%{address: "test", name: "Dom"},
%{address: "west", name: "Dom"},
%{address: "test", name: "Dominic"},
%{address: "west", name: "DomDom"}
]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With