首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过一些键和其他键的和值来合并散列数组

通过一些键和其他键的和值来合并散列数组
EN

Stack Overflow用户
提问于 2018-07-14 15:05:31
回答 6查看 599关注 0票数 2

我有一个像这样的数组

代码语言:javascript
复制
array = [
  {"point"=>6, "score"=>4, "team"=>"Challenger"},
  {"point"=>4, "score"=>2, "team"=>"INB"},
  {"point"=>2, "score"=>2, "team"=>"Super-11"},
  {"point"=>3, "score"=>7, "team"=>"INB"}
]

我想通过"team“合并散列,并将"point”和"score“的值相加。另外,如果point大于5,我还想在每个哈希中插入一个键"qualified“。因此,最终结果将是:

代码语言:javascript
复制
result= [
      {"point"=>6, "score"=>4, "qualified"=> "yes", "team"=>"Challenger"},
      {"point"=>7, "score"=>9, "qualified"=> "yes", "team"=>"INB"},
      {"point"=>2, "score"=>2, "qualified"=> "no", "team"=>"Super-11"}
    ]

任何帮助都将不胜感激。谢谢!

EN

回答 6

Stack Overflow用户

发布于 2018-07-14 17:52:46

另一种可能的解决方案:)

代码语言:javascript
复制
array.group_by { |item| item['team'] }.map do |_, items| 
  result = items.inject({}) { |hash, item| hash.merge(item) { |_, old, new| Integer(old) + new rescue old } }
  result.merge("qualified" => result['point'] > 5 ? "yes" : "no")
end
票数 3
EN

Stack Overflow用户

发布于 2018-07-14 15:45:18

代码语言:javascript
复制
result = array.group_by{|i| i['team']}
               .map do |k,v|
                 points = v.map{|i| i['point']}.inject(0, :+)
                 score = v.map{|i| i['score']}.inject(0, :+)
                 {
                   'point' => points, 
                   'score' => score, 
                   'qualified' => points > 5 ? 'yes' : 'no',
                   'team' => k
                 }
               end
票数 2
EN

Stack Overflow用户

发布于 2018-07-14 15:52:55

结合使用group_bymap应该会有所帮助

代码语言:javascript
复制
result = 
    array.group_by {|item| item['team'] }
         .map do |team, items|
             total_points = items.map{|item| item['point']}.reduce(0, :+)
             total_score = items.map{|item| item['score']}.reduce(0, :+)
             qualified = points > 5
             {
                 'point' => total_points, 
                 'score' => total_score, 
                 'qualified' => qualified ,
                 'team' => team
             }
          end
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51336139

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档