0

I have an array [[1, nil, nil], [1, 123, nil]] in which I am calling uniq on to remove duplicates based on the first value. However I want to specifically keep the duplicate that does not have nil for the second value (123 in this case)

my_array.uniq { |arr| arr.first.id }

Might return [[1, nil, nil]] but I want to ensure it returns [[1, 123, nil]]. Is there any way to do this rails style with uniq?

As thinkgruen stated below, I'm not too concerned with the case where there are 3 duplicates, since calling uniq again without the special condition is an option.

3
  • 1
    what would happen if the third element is [1, 123, nil] again? from what i understood, it will return [[1, 123, nil], [1, 123, nil]] but I think it's important to cover this case in your question as well. Commented Jun 10, 2021 at 20:47
  • Good point, there might be a better way but at the very least I can add another call to uniq without the condition. Commented Jun 10, 2021 at 20:51
  • 1
    I think the posted solution from cschroed is fine. because to use uniq the elements would have to be in order already, so that the first one is the one you want. Commented Jun 10, 2021 at 21:04

1 Answer 1

2

You may want to break this into multiple steps.

my_array = [[1, nil, nil], [1, 123, nil]]

# Group them
grouped = my_array.group_by(&:first)

# Decide which to keep
grouped.values.map do |group|
  # Detect one where the 2nd value isn't nil.  Otherwise take the first.
  group.detect { |object| !object[1].nil? } || group.first
end

 => [[1, 123, nil]]
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.