owaisqayum

owaisqayum

Iterating through a nested map without changing the structure

Hi,

I am having a map from which I want to extract values by the maximum length of values.

map = 
%{
  "A" => [
    {:b, "B", 1},
    {:b, "C", 1}
  ],
  "B" => [
    {:b, "D", 1}
  ],
  "C" => [
    {:b, "E", 1},
    {:b, "F", 1}
  ]
}

Here is my code:

 Enum.max_by(map, fn {key, value} -> length(value) end)

which gives me

{"A", [{:b, "B", 1}, {:b, "C", 1}]}

while I need to get a list of both key values that have maximum values. In this case, this should be the output

[
   {"A", [{:b, "B", 1}, {:b, "C", 1}]}, 
   {"C", [{:b, "E", 1}, {:b, "F", 1}]}

]

Marked As Solved

RudManusachi

RudManusachi

Enum.max_by returns at max 1 element =)
If you want to do it in a single cycle you probably want to do some custom reduce like

Enum.reduce(map, [], fn 
  item, [] -> [item]
  {_, val} = item, [{_, acc_val} | _] when length(val) > length(acc_val) -> [item]
  {_, val} = item, [{_, acc_val} | _] = acc when length(val) == length(acc_val) -> [item | acc]
  _, acc -> acc
end)

P. S. naming is hard :neutral_face:

Also Liked

stefanchrobot

stefanchrobot

Seems that max_by won’t work for you here, because:

If multiple elements are considered maximal, the first one that was found is returned.

So you need something like:

{count, values} =
  map
  |> Enum.group_by(fn {_key, values} -> length(values) end)
  |> Enum.max_by(fn {count, _values} -> count end)
owaisqayum

owaisqayum

Yeah it makes sense now. max_by will output the only instance maximum output. Enum.reduce seems like a better option.

RudManusachi

RudManusachi

To be honest, if Enum.reduce is a better option or not - I’m not sure :grinning_face_with_smiling_eyes:

I like the example of @stefanchrobot more, because it looks simpler and reads better =)

Where Next?

Popular in Questions Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&query=perfume&page=2, I would like to get: ...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
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
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
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
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

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
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
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
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
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
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
klo
Got a question about when to concat vs. prepending items to list then reversing to achieve appending. So i know lists boil down to [1 | ...
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New

We're in Beta

About us Mission Statement