Divide total with number of likes

Hey guys, so I have a list like so

[%{number_of_likes: 20, page_name: "Szilágyi György"}, %{number_of_likes: 33, page_name: "Szilágyi György"}, %{number_of_likes: 55, page_name: "Szilágyi György"}, %{number_of_likes: 57, page_name: "Szilágyi György"}, %{number_of_likes: 74, page_name: "Szilágyi György"}, %{number_of_likes: 110, page_name: "Szilágyi György"}, %{number_of_likes: 156, page_name: "Szilágyi György"}, %{number_of_likes: 183, page_name: "Szilágyi György"}, %{number_of_likes: 330, page_name: "Szilágyi György"}, %{number_of_likes: 445, page_name: "Szilágyi György"}, %{page_name: "Szilágyi György", total: 1463}]

I’m trying to get the total and divide it with number_of_likes, so I can get a list with new number_of_likes, can someone help me understand how to do it? Thanks

Why do all the maps in your list have the same page_name? Why does the last entry have different keys than the others? Since there are many different number_of_likes, which one is supposed to be the divisor? Please give some more information about what this list is supposed to represent.

1 Like

Hey @APB9785 sorry for that, so I need to number_of_like / total so total needs to be divisor here the end result should be

[%{calculated_value: total / number_of_likes, page_name: "Szilágyi György"}, ....]

I really can’t explain more it’s too complicated :joy: I guess I will just confuse you more.

How about this?

Enum.map(your_list, fn m ->
  Map.put(m, :calculated_value, m.total / m.number_of_likes)

Why do You expect a list as result? Your initial list always contains the same page name…

If it wasn’t the case, I would first Enum.group_by page_name.

Then, I can calculate the total and the number of likes with Enum.reduce.

Enum.reduce(list, {0, 0}, fn x, acc -> 
  case x do
    %{number_of_likes: nol} -> {elem(acc,0), elem(acc, 1) + nol}
    %{total: total} -> {elem(acc,0) + total, elem(acc, 1)}

It should return a tuple {total, number_of_likes}.

And You should have enough information to build the final result.

In your example, it returns {1463, 1463}, which is 1.

Probably I did not understand what You want :slight_smile:


Hey @kokolegorille thanks for the reply, yes indeed but those are daily number_of_likes, and both number_of_likes and total are for the give period of time, I didn’t want to explain the whole thing is confusing I just needed to solve this part for which @APB9785 posted a potential solution, thanks