views:

447

answers:

1

Hello

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. Any guidance with how to tackle this is much appreciated.

Thanks

+3  A: 
# 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 }
sepp2k
Works brilliantly. Thanks :)
aaronrussell