2013-04-22 54 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(:+) 
}}