2013-04-22 57 views
0

我有散列的数组...合并重复的数组项

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 
}] 

我需要用相同的keyword值巩固哈希。通过整合,我的意思是结合total_values。例如,合并上述数组后,应该只有一个散列,其中'keyword' => 'A''total_value => 60

回答

2
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 

输出:

{"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

这里是如何可以做到:

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} 
+0

我才意识到我的阵列,'keyword'和'total_value'不在引号中。此解决方案是否仍然有效? – mnort9 2013-04-22 21:42:45

+0

的意思是?请清除你自己。 – 2013-04-22 21:45:20

+0

对于#' – mnort9 2013-04-22 21:46:38

2

一个简单的方法是在将项添加到集合时执行此操作。开始添加一个项目,检查关键字是否存在。如果(a)它在那里,那么只需将新项目的total_value添加到其中。否则(b)向集合添加新项目。

0
array.group_by{|h| h["keyword"]} 
.map{|k, v| { 
    "keyword" => k, 
    "total_value" => v.map{|h| h["total_value"]}.inject(:+) 
}}