合并重复的数组项 [英] Consolidating duplicate array items

查看:113
本文介绍了合并重复的数组项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有散列的数组...

 阵列= [
{
    '关键字'=> '一个',
    total_value'=> 50
},
{
    '关键字'=> B,
    total_value'=> 25
},
{
    '关键字'=> 'C',
    total_value'=> 40
},
{
    '关键字'=> '一个',
    total_value'=> 10
},
{
    '关键字'=> 'C',
    total_value'=> 15
}]

我需要用相同的关键字价值,巩固哈希。通过整合,我的意思是结合 total_values​​ 。例如,上面的数组合并后,应该只有一个哈希与'关键字'=> 'A''total_value => 60


解决方案

 阵列= [
{
    '关键字'=> '一个',
    total_value'=> 50
},
{
    '关键字'=> B,
    total_value'=> 25
},
{
    '关键字'=> 'C',
    total_value'=> 40
},
{
    '关键字'=> '一个',
    total_value'=> 10
},
{
    '关键字'=> 'C',
    total_value'=> 15
}]M = array.inject(Hash.new(0))做| HS,I |
    HS [我['关键字'] + = I ['total_value']
    HS
结束
p M

输出:

  {A=> 60,B=→25,C=> 55}


  

通过巩固,我的意思是结合total_values​​。例如,上面的数组合并后,应该只有一个哈希以'关键字'=>'A'与'total_value => 60


下面是它是如何做到:

  M = array.each_with_object(Hash.new(0))做| H,OB |
     如果h ['关键字'] =='A'
        H ['total_value'] + = OB ['total_value']
        ob.update(H)
     结束
结束
p M
#=> {关键字=>A,total_value=> 60}

I have an array of hashes...

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

I need to consolidate the hashes with an identical keyword value. 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

解决方案

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

Output:

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

Here is how it can be done:

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}

这篇关于合并重复的数组项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆