otuv

otuv

Grouping and extract values from list of maps

Hi,
I have a list of maps such as:

[%{x: a, y: 1}, %{x: a, y: 1}, %{x: b, y: 0}, %{x: b, y: 1}]

From this I would like to find out how many 1s a and b have respectively

ie. resulting in something like:

[a: 2, b:1]

(or something to that effect)

I have accomplished this using rather brute force and un-elixirish ways and do feel there should be a rather elegant solution but it has eluded me so far and any help is appreciated.

Marked As Solved

factoryd

factoryd

One, pretty straight-forward, way to accomplish what you’re after is to think in the steps of what you want.

  1. You want to group your list into keys and the values of each unique key
  2. You want to count the unique values (in your example, you want to count the 1s)

So you have something like this:

[%{x: :a, y: 1}, %{x: :a, y: 1}, %{x: :b, y: 0}, %{x: :b, y: 1}]
    |> Enum.group_by(fn %{x: x} -> x end, fn %{y: y} -> y end)
    |> IO.inspect(label: "grouped")
    |> Enum.reduce([], fn {key, values}, acc ->
      acc ++ [key, Enum.count(values, fn x -> x == 1 end)]
    end)

Now you may think this is very specific to finding the count of 1s. And you’re right.

To make it more general is just as easy.
Just think of the steps you need to take to get what you want.

It’s exactly as above with an extra step of finding the values of n. …and use some functions to be kind to others. :stuck_out_tongue:

defmodule Playground do
  def hello do
    [%{x: :a, y: 1}, %{x: :a, y: 1}, %{x: :b, y: 0}, %{x: :b, y: 1}]
    |> count_values()
    |> count_value(1)
    |> IO.inspect(label: "count of 1s by key")
  end

  defp count_values(list) do
    list
    |> Enum.group_by(fn %{x: x} -> x end, fn %{y: y} -> y end)
    |> IO.inspect(label: "values grouped by key")
    |> Enum.reduce([], fn {key, values}, acc ->
      counts =
        Enum.reduce(values, %{}, fn value, acc ->
          Map.update(acc, value, 1, &(&1 + 1))
        end)

      acc ++ [{key, counts}]
    end)
    |> IO.inspect(label: "values counted")
  end

  defp count_value(list, n) do
    Enum.reduce(list, [], fn {key, values}, acc ->
      count =
        values
        |> Enum.filter(fn {value, _} -> value == n end)
        |> Enum.map(fn {_, count} -> count end)
        |> IO.inspect(label: "#{key} #{n}s")

      # ensure we use zero if we have no results in `count`
      count =
        case count do
          [n] -> n
          _ -> 0
        end

      acc ++ [{key, count}]
    end)
  end
end

Now that you have your answers, clean it up however you feel is necessary.

Cheers!

Also Liked

shanesveller

shanesveller

What did you try already? What felt less-than-ideal to you about it?

I’d probably just start with an Enum.reduce and go from there, because this is pretty similar conceptually to the “count the occurrence of a letter or word in a string” problem that frequently appears in coding koans/challenges/exercises.

dimitarvp

dimitarvp

Are a and b variables? Your given code snippet is not valid Elixir otherwise. They could be atoms (:a and :b) or strings ("a" and "b").

otuv

otuv

Now I feel rather embarrassed. I simply missed that there was a count/2. In hindsight this is rather obvious in language like this.

Where Next?

Popular in Questions Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
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
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
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
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
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
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

siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
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 39467 209
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
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
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
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement