michaelb

michaelb

Filter list of maps

Hello!
I’m trying to filter list of maps to remove items where value of key was declared previously in this list. List that I have:

list = [%{
    "distance" => "4",
    "source" => "source_1",
},
%{
    "distance" => "2",
    "source" => "source_1",
},
%{
    "distance" => "5",
    "source" => "source_2",
},
%{
    "distance" => "1",
    "source" => "source_2",
},
%{
    "distance" => "2",
    "source" => "source_2",
}]

List what I want to get:

[%{
    "distance" => "4",
    "source" => "source_1",
},
%{
    "distance" => "5",
    "source" => "source_2",
}]

I tried next code:

sources = []
list
|> Enum.filter(fn p ->
    if p["source"] in sources do
        false
    else
        sources ++ p["source"]
        true
    end
end) |> IO.inspect

But looks like list “sources” not accessed from Enum.filter. Probably there exist more correct solution for this?

Marked As Solved Switch mode

amnu3387

amnu3387

There’s Enum.uniq_by/2 that you can use, as in Enum.uniq_by(list, fn(%{"source" => s}) -> s end)

The reason your filter doesn’t work is because you’re building the list as you enumerate the elements and you can’t mutate the variable sources. You can achieve what you want with a reduction, where you keep track of them as you exemplified:

{_, new_list} = Enum.reduce(list, {[], []}, fn(%{"source" => s} = el, {sources, acc}) ->
                               if(s in sources, do: {sources, acc}, else: {[s | sources], [el | acc]}) 
                end)

final = :lists.reverse(new_list)

Also Liked

vlarok

vlarok

  def single(list) do
   Enum.uniq_by(list, &(%{"source" => &1.source}))
  end
kokolegorille

kokolegorille

Here is my one line ugly try :slight_smile:

iex> list |> Enum.reduce(%{}, fn %{"source" => s} = x, acc -> Map.put_new(acc, s, x) end) |> Enum.map(fn {_k, v} -> v end)        
[
  %{"distance" => "4", "source" => "source_1"},
  %{"distance" => "5", "source" => "source_2"}
]

I use Map.put_new to ensure only first source is persisted

OvermindDL1

OvermindDL1

For note, your sources ++ p["source"] expression is evaluated here but the result is thrown away since it’s not being returned.

And it looks like you aren’t just wanting a unique one based on the name, but also the one with the highest value in each set, thus I’d probably do either this:

Enum.group_by(list, & &1["source"]) |> Enum.map(fn {_, v} -> Enum.max_by(v, & &1["distance"]) end)

Or this:

Enum.sort_by(list, & {&1["source"], &1["distance"]}, &>/2) |> Enum.dedup_by(& &1["source"])

Or any of a variety of other ways. :slight_smile:

Last Post!

formingform

formingform

I think this is a much simpler approach: apply Enum.uniq_by/2 twise.

Enum.uniq_by(list, fn elem -> elem["distance"] end)
|> Enum.uniq_by(fn elem -> elem["source"] end)

Where Next?

Trending in Questions Top

jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
silverdr
Using Phoenix.LiveView.TagEngine as an EEx.Engine is deprecated! To compile HEEx, use Phoenix.LiveView.TagEngine.compile/2 instead. Sta...
New
saveman71
Hello ! We want new/edit form pages to POST/PUT to their own URL rather than the resources REST defaults (post /things, put /things/:id)...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
michallepicki
I am using Oban and occasionally, shortly after a deployment, a handful of jobs can fail because of dependency on other parts of the syst...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve. They are GUI (Emerge) and State management (S...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
akoutmos
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New

We're in Beta

About us Mission Statement