aar*_*ell 1 ruby arrays merge multidimensional-array
我有一个数组,为了论证,看起来像这样:
a = [[1,100], [2,200], [3,300], [2,300]]
Run Code Online (Sandbox Code Playgroud)
在这四个子数组中,我想合并任何第一个元素是重复的地方.所以在上面的例子中我想合并第二和第四个子阵列.但是,需要注意的是,匹配子阵列中的第二个元素不同,我想保持较高的值.
所以,我希望看到这个结果:
a = [[1,100], [3,300], [2,300]]
Run Code Online (Sandbox Code Playgroud)
这个小难题比我的Ruby技能略高,所以我转向社区寻求帮助.任何有关如何解决这个问题的指导都非常感谢.
谢谢
# 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 }
Run Code Online (Sandbox Code Playgroud)