合并重复的数组项 [英] Consolidating duplicate array items
问题描述
我有散列的数组...
阵列= [
{
'关键字'=> '一个',
total_value'=> 50
},
{
'关键字'=> B,
total_value'=> 25
},
{
'关键字'=> 'C',
total_value'=> 40
},
{
'关键字'=> '一个',
total_value'=> 10
},
{
'关键字'=> 'C',
total_value'=> 15
}]
我需要用相同的关键字
价值,巩固哈希。通过整合,我的意思是结合 total_values
。例如,上面的数组合并后,应该只有一个哈希与'关键字'=> 'A'
与'total_value => 60
阵列= [
{
'关键字'=> '一个',
total_value'=> 50
},
{
'关键字'=> B,
total_value'=> 25
},
{
'关键字'=> 'C',
total_value'=> 40
},
{
'关键字'=> '一个',
total_value'=> 10
},
{
'关键字'=> 'C',
total_value'=> 15
}]M = array.inject(Hash.new(0))做| HS,I |
HS [我['关键字'] + = I ['total_value']
HS
结束
p M
输出:的
{A=> 60,B=→25,C=> 55}
通过巩固,我的意思是结合total_values。例如,上面的数组合并后,应该只有一个哈希以'关键字'=>'A'与'total_value => 60
块引用>下面是它是如何做到:
M = array.each_with_object(Hash.new(0))做| H,OB |
如果h ['关键字'] =='A'
H ['total_value'] + = OB ['total_value']
ob.update(H)
结束
结束
p M
#=> {关键字=>A,total_value=> 60}I have an array of hashes...
array = [ { 'keyword' => 'A', 'total_value' => 50 }, { 'keyword' => 'B', 'total_value' => 25 }, { 'keyword' => 'C', 'total_value' => 40 }, { 'keyword' => 'A', 'total_value' => 10 }, { 'keyword' => 'C', 'total_value' => 15 }]
I need to consolidate the hashes with an identical
keyword
value. By consolidate, I mean combinetotal_values
. For example, after consolidation of the above array, there should only be one hash with'keyword' => 'A'
with a'total_value => 60
解决方案array = [ { 'keyword' => 'A', 'total_value' => 50 }, { 'keyword' => 'B', 'total_value' => 25 }, { 'keyword' => 'C', 'total_value' => 40 }, { 'keyword' => 'A', 'total_value' => 10 }, { 'keyword' => 'C', 'total_value' => 15 }] m = array.inject(Hash.new(0)) do |hs,i| hs[i['keyword']] += i['total_value'] hs end p m
Output:
{"A"=>60, "B"=>25, "C"=>55}
By consolidate, I mean combine total_values. For example, after consolidation of the above array, there should only be one hash with 'keyword' => 'A' with a 'total_value => 60
Here is how it can be done:
m = array.each_with_object(Hash.new(0)) do |h,ob| if h['keyword'] == 'A' h['total_value'] += ob['total_value'] ob.update(h) end end p m #=> {"keyword"=>"A", "total_value"=>60}
这篇关于合并重复的数组项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!