簡體   English   中英

Ruby將具有相同鍵和多個值的哈希數組組合在一起

[英]Ruby combine array of hashes with the same key and multiple values

我有以下數組,它實際上是兩個數組的組合。 我的目標是可以將雇員編號為898989的2個散列進行組合,並且可以將它們的計數加在一起並將它們的類型都更改為兩者。 我嘗試了下面與我想要的代碼接近的代碼,但是我丟失了哈希的其他值。 有沒有一種簡單的方法可以映射所有值並進行像添加計數一樣的操作?

combined = [{"@rid"=>"#-2:1", "employeeId"=>   "898989", "count"=>1, :type=>"wiki"  },
       {"@rid"=>"#-2:3", "employeeId"=>  "2423213", "count"=>7, :type=>"search"},
       {"@rid"=>"#-2:2", "employeeId"=>   "555555", "count"=>2, :type=>"search"},
       {"@rid"=>"#-2:5", "employeeId"=>   "898989", "count"=>2, :type=>"search"},
       {"@rid"=>"#-2:1", "employeeId"=>  "5453454", "count"=>1, :type=>"search"},
       {"@rid"=>"#-2:4", "employeeId"=>"987654321", "count"=>1, :type=>"search"}]

merged_array_hash = combined.group_by { |h1| h1["employeeId"] }.map do |k,v|
    { "employeeId" => k, :types =>  v.map { |h2| h2[:type] }.join(", ") }
end

merged_array_hash最終是:

[{employeeId: "898989",types: "wiki, search"},
{employeeId: "2423213",types: "search"},
{employeeId: "555555",types: "search"},
{employeeId: "5453454",types:"search"},
{employeeId: "987654321",types: "search"}]

我想要得到的是:

[{employeeId: "898989",type: "both", count: 2},
{employeeId: "2423213",type: "search", count: 7},
{employeeId: "555555",type: "search", count: 2},
{employeeId: "5453454",type:"search", count: 1},
{employeeId: "987654321",type: "search", count: 1}]

不漂亮,但是可以完成工作:

combined.group_by { |h1| h1["employeeId"] }.map do |k,v|
  types = v.map { |h2| h2[:type] }  
  count = v.sum { |x| x['count'] } 

  { employeeId: k, 
    types: (types.length == 1 ? types[0] : 'both'), 
    count: count }  

end  

=> [{:employeeId =>"898989", :types=>"both", :count=>3},
    {:employeeId =>"2423213", :types=>"search", :count=>7},
    {:employeeId =>"555555", :types=>"search", :count=>2},
    {:employeeId =>"5453454", :types=>"search", :count=>1},
    {:employeeId =>"987654321", :types=>"search", :count=>1}]

同樣不漂亮,也會完成工作,可能更具可讀性

hash = {}
combined.each do |h|
  employeeId, count, type = h.values_at("employeeId", "count", :type)
  if hash.include? employeeId
    hash[employeeId][:count] += count
    hash[employeeId][:type] = "both"  #assumes duplicates can only occur if item is in both lists
  else
    hash[employeeId] = { :employeeId => employeeId, :type => type, :count => count }
  end
end
hash.values

測試:

[{:employeeId=>"898989", :type=>"both", :count=>3},
{:employeeId=>"2423213", :type=>"search", :count=>7},
{:employeeId=>"555555", :type=>"search", :count=>2},
{:employeeId=>"5453454", :type=>"search", :count=>1},
{:employeeId=>"987654321", :type=>"search", :count=>1}]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM