owaisqayum

owaisqayum

How to find unique values by two parameters?

I am having a List of Tuples which contains some data and the last element of each tuple is a Map. Now, i want to remove duplications and find the unique values by maximum value %{u: [{_, _, value}]} in the map.

[
  {"Elixir", 2019,
   %{
     values: %{u: [{:b, :r1,  1}]},
     status: true
   }},
  {"Elixir", 2020,
   %{
     values: %{
       u: [
         {:b, :r2, 1},
         {:b, :r3, 2}
       ]
     },
     status: true
   }},
  {"Elixir", 2020,
   %{
     values: %{
       u: [
         {:b, :r2, 2},
         {:b, :r3, 2}
       ]
     },
     status: true
   }}
]

The final output should look like

[
  {"Elixir", 2019,
   %{
     values: %{u: [{:b, :r1,  1}]},
     status: true
   }},
  {"Elixir", 2020,
   %{
     values: %{
       u: [
         {:b, :r2, 2},
         {:b, :r3, 2}
       ]
     },
     status: true
   }}
]

So it also removed the duplicated {elixir, 2020} and left behind the tuple having the maximum value of 2.

I tried it using groups but I don’t how to go inside the maps and then compare two different tuples.

Thanks

Most Liked

APB9785

APB9785

Creator of ECSx

Actually by hard coded i mean that the parameters won’t always be name and year. It can be one or more arguments.

When you use tuples, you are saying that the data format (e.g. number of arguments) will always be the same. If you plan on having additional arguments, you should be using a List, or preferably a Map/Struct so anyone else reading your code can easily see what the values are supposed to represent.

The difference between [2, 1] and [2, 2] is that the later is the updated value of r1 hence updating it by + 1.

If r is being incremented, you should not use atoms for this, but an Integer.

which structure would be more accessible, should i use Keyword Lists or Structs. Kindly help me on that.

Some of your key names are ambiguous - like, I have no idea, what values.u means, or what :b signifies, and I’m only just now learning the significance of :r1, :r2 etc… So it’s difficult for me to say what specifically would be the best way to structure your data, but here is a try:

%{
  language: "Elixir",
  year: 2020,
  user_values: [
    %{type: "b", revision: 2, value: 1}
    %{type: "b", revision: 3, value: 2},
  ],
  other_param: "foo",
  status: true
}

and here is the code I gave above, updated for this structure:

defmodule Test do
  def unique(todo, seen \\ %{})

  def unique([], seen), do: Map.values(seen)

  def unique([h | t], seen) do
    prev_best = Map.get(seen, {h.language, h.year})

    if is_nil(prev_best) or latest_revision(h) >= latest_revision(prev_best) do
      new_seen = Map.put(seen, {h.language, h.year}, h)
      unique(t, new_seen)
    else
      unique(t, seen)
    end
  end

  def latest_revision(map) do
    Enum.max_by(map.user_values, & &1.revision)
  end
end
APB9785

APB9785

Creator of ECSx

Elixir and 2020 : these are just the values and it can be as many values.

You say these are the values, but then you have a different map called :values. Whatever is the “payload” - the values you need for your API, those should be kept together and made easily accessible.

Last Value in Tuple : Last value in the tuple will be a map, struct, keyword list which will always have two keys i.e. values and status .

You will notice that there is not even a function in Elixir to get the last value from a tuple. You must hard-code the specific index you want. This is because you are not supposed to have variable-length tuples. (I already mentioned this in my previous post)

u : It is a key for storing values. we can have many different keys like j , s , c which means union, join, select or cross product.

Why does it matter which query type was used? It doesn’t make sense to me that you would do multiple queries for the same data, and merge them into the same entry, but then still have problems with duplicate entries.

{:b, :r2, 1} : :r2 is just the unique identifier while 1 is the count of elixir and 2020 in the table where the greater value tuple will replace the smaller value.

If :r2 is a unique identifier, then it shouldn’t be hidden away inside a tuple, it should be used as a key in a map, which will ensure that only one can exist at any given time. Then if a new :r2 payload comes in, your code should decide right then whether or not to replace the existing one.

APB9785

APB9785

Creator of ECSx

I use elem(tuples, tuple_size(tuple, -1))

Yes I know there is this workaround, but it is not the intended use of tuples. From the docs:

Tuples are intended as fixed-size containers for multiple elements. To manipulate a collection of elements, use a list instead. Enum functions do not work on tuples.

But then how will I utilize the :u or :j … Thats a bit of a confusing part. It’s necessary for my structure.

If you want advice on this, you must give us some more details about why it is necessary (i.e. how this data is used by your API)

Where Next?

Popular in Questions Top

chokchit
** (DBConnection.ConnectionError) connection not available and request was dropped from queue after 2733ms. You can configure how long re...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lists...
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
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
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
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New

Other popular topics Top

AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New
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
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
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
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30877 112
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
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
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
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
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

We're in Beta

About us Mission Statement