# Sum of the second elements in the list of pairs

Let's say I have a list

list = {{0,1},{0,2},{0,3},{1,2},{1,4},{2,3},{2,5},{3,4},{5,9}}


I want to get a new_list

new_list = {{0,6},{1,6},{2,8},{3,4},{5,9}}


In this new_list the second element of each pair is a sum of second elements from the original list in which the first elements are similar:

{0,1},{0,2},{0,3} -> {0,1+2+3} -> {0,6};
{1,2},{1,4} -> {1,2+4} -> {1,6};
{2,3},{2,5} -> {2,3+5} -> {2,8};
{3,4} -> {3,4}


Is there a way to do this?

Using GatherBy:

list = {{0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 4}, {2, 3}, {2, 5}, {3,
4}, {5, 9}}

{#[[1, 1]], Total[#[[All, 2]]]} & /@ GatherBy[list, First]


Using Reap/Sow:

a = Union@(First /@ list)
b = Plus @@@ Last@Reap@Scan[Sow[Last@#, First@#] &, list]
Transpose[{a, b}]


Using Merge:

List @@@ (Merge[Rule @@@ list, Total] // Normal)


Result:

{{0, 6}, {1, 6}, {2, 8}, {3, 4}, {5, 9}}

GroupBy[list, First -> Last, Total]


<|0 -> 6, 1 -> 6, 2 -> 8, 3 -> 4, 5 -> 9|>

To get to a list form:

KeyValueMap[List, GroupBy[list, First -> Last, Total]]


{{0, 6}, {1, 6}, {2, 8}, {3, 4}, {5, 9}}