njwest

njwest

Comparing, Combining, and Deduping Lists of Strings within a List

Still fairly new to Elixir and am coming from OOP, so bear with me here…

I have a list of lists of strings, each with a length of 2, ie:

list = [ ["Tony", "Glove"] , ["Mark", "Shirt"], ["Tony", "Hat"] ]

and I want to combine and dedup the lists that have the same value in index[0], so the list above would turn into:

convert_list(list) = [ ["Tony", "Glove", "Hat"], ["Mark", "Shirt"] ]

My first attempt was turning each list into a MapSet, then using:
if MapSet.member do _nothing else MapSet.union(Enum.at(list, x),Enum.at(list,y)

within a recursive for x <- 0..Enum.count(list) function, but I am pretty much in over my head on this one.

Any help/guidance would be greatly appreciated!

Marked As Solved

OvermindDL1

OvermindDL1

What immediately jumps to my mind is:

╰─➤  iex
Erlang/OTP 20 [erts-9.1] [source] [64-bit] [smp:2:2] [ds:2:2:10] [async-threads:10] [hipe] [kernel-poll:false]

Interactive Elixir (1.6.0-dev) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> list = [ ["Tony", "Glove"] , ["Mark", "Shirt"], ["Tony", "Hat"] ]                     
[["Tony", "Glove"], ["Mark", "Shirt"], ["Tony", "Hat"]]
iex(2)> list |> Enum.group_by(&hd/1) |> Enum.map(&Enum.uniq(List.flatten(elem(&1, 1))))
[["Mark", "Shirt"], ["Tony", "Glove", "Hat"]] 
iex(3)> 

Also Liked

pma

pma

To guarantee list values are deduped one option is to use a MapSet as collector, or just add Enum.uniq/1 to previous solution.

list
|> Enum.reduce(%{}, fn [k, v], m -> Map.update(m, k, MapSet.new([v]), &MapSet.put(&1, v)) end)
|> Enum.map(fn {k, v} -> [k | Enum.to_list(v)] end)
kokolegorille

kokolegorille

Whenever I need to check for key unicity, I would use a map. I would also use Enum.reduce… with some translation due to atom key. The last command line transform the map back to a list.

iex> list 
|> Enum.reduce(%{}, fn [k, v], acc -> Map.update(acc, String.to_atom(k), [v], fn y -> [v | y] end) end) 
|> Enum.map(fn {k, v} -> [to_string(k) | v] end)
[["Mark", "Shirt"], ["Tony", "Hat", "Glove"]]

You might need to reverse some order, as I always add to the head of a list [h | t]

kokolegorille

kokolegorille

In fact, I don’t even need to transform the keys…

iex> list 
|> Enum.reduce(%{}, fn [k, v], acc -> Map.update(acc, k, [v], fn y -> [v | y] end) end) 
|> Enum.map(fn {k, v} -> [k | v] end)
kokolegorille

kokolegorille

That is true, your solution is nicer with the use of MapSet :slight_smile:

kokolegorille

kokolegorille

That is more complex.

A hint would be to get all root keys, by filtering the keys that does not exists in the list of values.

values = list2 |> Enum.map(& List.last(&1))
root_keys = list2 |> Enum.map(& List.first(&1)) |> Enum.filter(& !Enum.member?(values, &1)) |> Enum.uniq

Then, in some loop, treat the root keys as is, and the others as belonging to a sub tree.

Not to mention edge case like this…

[“Mark”, “Wallet”], [“Tony”, “Wallet”]

Where Next?

Popular in Questions Top

bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
Werner
Hi, I’m using Ubuntu 18.04 and after updating to OTP-24.0 yesterday i have this warning when I run “mix local.hex”: 14:57:30.512 [warn] ...
New
dokuzbir
Hello, I am trying to convert my lists to string without losing brackets.For start i have 3 map. They look like these buyer = %{ id: ...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
makeitrein
Hey all, just started picking up Elixir last week and am writing a scraper as a learning project. Baby step #1 is extracting the number ...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
sabri
Can someone explain the settings of pool_size of Ecto in config file? and what is the recommend size? Thanks
New

Other popular topics Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 27727 240
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New

We're in Beta

About us Mission Statement