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

marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
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
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lists...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
nobody
How to bind a phoenix app to a specific ip address? could not find anything about that, nowhere, unfortunately, but for me this is quite...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; somethi...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

Other popular topics Top

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
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
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
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New

Latest on Elixir Forum

We're in Beta

About us Mission Statement