Question: I've got a ruby hash like this

```

[{user_id: 3, purchase: {amount: 2, type_id:3, name:"chocolate"},
 {user_id: 4, purchase: {amount: 1, type_id:3, name: "chocolate"},
 {user_id: 5, purchase: {amount: 10, type_id:4, name: "penny-candy"}]

```

I want to take the array and merge by the type\_id, sum the amounts, connect the user to the amounts, so the end result would be

```

[{type_id: 3, name: "chocolate", total_amounts:3, user_purchases[{user_id:3, amount:2},user_id:4,amount:1}],
{type_id:4, name: "penny-candy", total_amounts: 10, [{user_id:5,amount:2}]}]

```

how would I go from one type of output to the other?

Answer: 
It's a group\_by problem. I'll give you 2:

```
new_array = old_array.group_by{|x| x[:purchase][:type_id]}.values.map do |group|
  {:type_id => group[0][:purchase][:type_id], :total_amounts => group.map{|g| g[:purchase][:amount]}.reduce(&:+)}
end

```

and leave the other 2 as an exercise
I would first simplify it:

```
old_arr =  [
 {user_id: 3, purchase: {amount: 2, type_id:3, name:"chocolate"}},
 {user_id: 4, purchase: {amount: 1, type_id:3, name: "chocolate"}},
 {user_id: 5, purchase: {amount: 10, type_id:4, name: "penny-candy"}}]

intermediate_arr = old_arr.map{ |h| [h[:user_id], h[:purchase][:amount], h[:purchase][:type_id], h[:purchase][:name]]}

```

This creates the following array:

```
[[3, 2, 3, "chocolate"], [4, 1, 3, "chocolate"], [5, 10, 4, "penny-candy"]]

```

Now you can format it any way you want. I chose to format it like this:

```
new_hash = {}
intermediate_arr.each do |arr|
  if new_hash[arr[2]]
    new_hash[arr[2]][:purchase] += [{user_id: arr[0], amount: arr[1]}]
  else
    new_hash[arr[2]] = {name: arr[3], purchase: [{user_id: arr[0], amount: arr[1]}]}
  end
end

```

Giving:

```
{3=>{:name=>"chocolate", :purchase=>[{:user_id=>3, :amount=>2}, {:user_id=>4, :amount=>1}]}, 4=>{:name=>"penny-candy", :purchase=>[{:user_id=>5, :amount=>10}]}}

```