0

i have array of hash like this :

a = [{:transaction_type=>"nationalvoice", :transaction_duration=>181}, {:transaction_type=>"nationalvoice", :transaction_duration=>60}, {:transaction_type=>"call", :transaction_duration=>200}]

how to merge value based transaction_type = "nationalvoice" ?

i want get result like this :

a = [{:transaction_type=>"nationalvoice", :transaction_duration=>241}, {:transaction_type=>"call", :transaction_duration=>200}]

how do that?

thanks before

3 Answers 3

2

Do as below :

a = [{:transaction_type=>"nationalvoice", :transaction_duration=>181}, {:transaction_type=>"nationalvoice", :transaction_duration=>60}, {:transaction_type=>"call", :transaction_duration=>200}]


array_merge_hash = a.group_by { |hash1| hash1[:transaction_type] }.map do |_,v|
  v.inject do |ele_hash2,ele_hash1| 
     ele_hash2.merge(ele_hash1) {|k,o,n| k == :transaction_duration ? o+n : o }
  end
end
Sign up to request clarification or add additional context in comments.

Comments

0

Using Enumerable#group_by:

a = [
  {:transaction_type=>"nationalvoice", :transaction_duration=>181},
  {:transaction_type=>"nationalvoice", :transaction_duration=>60},
  {:transaction_type=>"call", :transaction_duration=>200},
]

groups = a.group_by { |h| h[:transaction_type] }
# => {"nationalvoice"=>[
#      {:transaction_type=>"nationalvoice", :transaction_duration=>181},
#      {:transaction_type=>"nationalvoice", :transaction_duration=>60}
#    ],
#    "call"=>[
#      {:transaction_type=>"call", :transaction_duration=>200}
#    ]}

merged_hashes = groups.map { |k, hashes|
  total = hashes.map { |h| h[:transaction_duration] }.reduce(:+)
  {transaction_type: k, transaction_duration: total} # merged hash
}

# => [{:transaction_type=>"nationalvoice", :transaction_duration=>241},
#     {:transaction_type=>"call", :transaction_duration=>200}]

Comments

0

You could also use Enumerable#each_with_object

a =[{:transaction_type=>"nationalvoice", :transaction_duration=>181}, {:transaction_type=>"nationalvoice", :transaction_duration=>60}, {:transaction_type=>"call", :transaction_duration=>200}]
n = a.each_with_object({}) do |obj,hsh|
   hsh[obj[:transaction_type]] ? hsh[obj[:transaction_type]][:transaction_duration]+= obj[:transaction_duration].to_i : hsh[obj[:transaction_type]]=obj
end
print n.values

# [{:transaction_type=>"nationalvoice", :transaction_duration=>241}, {:transaction_type=>"call", :transaction_duration=>200}]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.