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

albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
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
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
mathew4509
I have a list say x = ["23gh", "56kh", "97mh"] I would like to pass each element to Val in each iteration. Say, in iteration 1 -------...
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
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
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

Other popular topics Top

yurko
Here are few pieces of (common) Linux knowledge that we use for reasonably small one server apps. We use Ubuntu but this should work for ...
New
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
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
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
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
magnetic
Hey :wave:t3: Elixir community, I’ve been learning Elixir, and working on some side projects. My editor of choice is VSCode, and althoug...
New

We're in Beta

About us Mission Statement