1

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

1 Answer 1

5
# 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 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.