简体   繁体   English

如何在Ruby中合并子数组中的子数组?

[英]How to merge sub-arrays within an array in Ruby?

I have an array which for arguments sake looks something like this: 我有一个数组,出于参数考虑,它看起来像这样:

a = [[1,100], [2,200], [3,300], [2,300]]

Of those four sub-arrays, I would like to merge any where the first element is a duplicate. 在这四个子数组中,我想合并第一个元素为重复项的任何子数组。 So in the example above I would like to merge the 2nd and the 4th sub-arrays. 因此,在上面的示例中,我想合并第二和第四子数组。 However, the caveat is that where the second element in the matching sub-arrays is different, I would like to maintain the higher value. 但是,需要注意的是,在匹配子数组中第二个元素不同的情况下,我想保持较高的值。

So, I would like to see this result: 因此,我希望看到以下结果:

a = [[1,100], [3,300], [2,300]]

This little conundrum is a little above my Ruby skills so am turning to the community for help. 这个小难题超出了我的Ruby技能,因此请向社区寻求帮助。 Any guidance with how to tackle this is much appreciated. 任何有关如何解决此问题的指导都将受到赞赏。

Thanks 谢谢

# Get a hash that maps the first entry of each subarray to the subarray
# requires 1.8.7+ or active_support (or facets, I think)
hash = a.group_by { |first, second| first }
# Take each entry in the hash and select the biggest entry for each unique key
hash.map {|k,v| v.max }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM