繁体   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