How to group elements of sub-arrays based on two elements

How to group elements of sub-arrays based on two elements



I have an input as follows:


input = [
["account1",10,"Dr"],
["account1",20,"Dr"],
["account2",15,"Cr"],
["account1",25,"Cr"],
["account2",10,"Dr"],
["account1",10,"Cr"]
]



I am trying to get the sums by account and transaction type, i.e., Dr or Cr. I need an output as below:


Dr


Cr


output =
["account1","Dr"] => 30,
["account1","Cr"] => 35,
["account2","Dr"] => 10,
["account2","Cr"] => 15



I can sum the amount based on only account using:


input.each_with_object(Hash.new(0))
# => "account1"=>65, "account2"=>25




3 Answers
3



You can do so:


input.each_with_object(Hash.new(0)) (f,g,i), h

=> ["account1", "Dr"]=>30, ["account2", "Cr"]=>15, ["account1", "Cr"]=>35, ["account2", "Dr"]=>10


input.group_by acc,_,title.
transform_values
#=> ["account1", "Dr"]=>30, ["account2", "Cr"]=>15, ["account1", "Cr"]=>35,
# ["account2", "Dr"]=>10



The first step is the following.


input.group_by acc,_,title
#=>
# ["account1", "Dr"]=>[["account1", 10, "Dr"], ["account1", 20, "Dr"]],
# ["account2", "Cr"]=>[["account2", 15, "Cr"]],
# ["account1", "Cr"]=>[["account1", 25, "Cr"], ["account1", 10, "Cr"]],
# ["account2", "Dr"]=>[["account2", 10, "Dr"]]
#


output = Hash.new(0) # set a default value of zero, avoiding nil
input.each do |account, amount, transaction|
output[[account, transaction]] += amount
end

output # ["account1", "Dr"]=>30, ["account2", "Cr"]=>15, ["account1", "Cr"]=>35, ["account2", "Dr"]=>10






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)