newbie1

newbie1

How to get min values structs from array?

Hi, I have an array of structs:

array = [%{count: 1, img: 1}, %{count: 1, img: 2}, %{count: 3, img: 3},
 %{count: 1, img: 4}]```

What i want is return the struct with minimum value. if there is more than 1 struct which contains minimum value like “1” it should return all of them. in this case it should return:

array = [%{count: 1, img: 1}, %{count: 1, img: 2}, %{count: 1, img: 4}]

The check is on “count”

Thanks in advance

Most Liked

peerreynders

peerreynders

A list of maps actually …

There is a Enum.min_by/3 but that returns only a single value. But all these functions are linked to the source so you can find out how that works - it turns out that it is based on - Lists.foldl/3 - a function you can use to solve your problem (or Enum.reduce/3).

Now both reduce and foldl work on an accumulator value - my choice would be a tuple like (min_value, [maps_with_min_value]). So every time a new element of the list is inspected a decision has to be made:

  • Is this lower than min_value? If yes, start a new list for the new min value resulting in a tuple (new_min_value, [map_with_new_min_value])
  • Is this equal to min_value? If yes, add the new map to the list, i.e. (min_value,[new_map| others])
  • Otherwise leave the tuple unchanged.

Note also that you should also account for being handed an empty list - i.e. there is no minimum - then the resulting list should simply be empty. But if there are any maps to process in the list you simply take the first map as your initial minimum for the accumulator and process the remainder of the list with foldl or reduce.

PS: With pattern matching you can just use the list as an accumulator (i.e. peek inside the first element of the list rather than holding min_value separately).

OvermindDL1

OvermindDL1

If you want it to output in exactly the same output as you stated (so the same order as the original) then I’d just do this:

╰─➤  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.1) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> array = [%{count: 1, img: 1}, %{count: 1, img: 2}, %{count: 3, img: 3}, %{count: 1, img: 4}]
[
  %{count: 1, img: 1},
  %{count: 1, img: 2},
  %{count: 3, img: 3},
  %{count: 1, img: 4}
]
iex(2)> {_, array} = Enum.reduce(Enum.reverse(array), {nil, []}, fn
...(2)>   %{count: count} = v, {c, a} when count < c -> {count, [v]}
...(2)>   %{count: count} = v, {count, a} -> {count, [v | a]}
...(2)>   _, acc -> acc
...(2)> end)
{1, [%{count: 1, img: 1}, %{count: 1, img: 2}, %{count: 1, img: 4}]}

peerreynders

peerreynders

It’s worth noting that this approach relies on term ordering:

number < atom < reference < function < port < pid < tuple < map < list < bitstring

i.e. because nil is actually :nil (i.e. an atom)

number < nil

is always true

Where Next?

Popular in Questions Top

_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
mgjohns61585
Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from ...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
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
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
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New

Other popular topics Top

hakarabakara1
I have three modules, a Business which is associated Tags and Categories though join tables business_tags and business_categories. I inte...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 39297 209
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
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
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New

We're in Beta

About us Mission Statement