0

I have an array of hashes:

a = [{'id'=> '1', 'subject'=> 'this is subject 1', 'orig_id'=> 123, 'parent_id'=> 123}, 
     {'id'=> '2', 'subject'=> 'this is subject 2', 'orig_id'=> 456, 'parent_id'=> 123},
     {'id'=> '3', 'subject'=> 'this is subject 3', 'orig_id'=> 789, 'parent_id'=> 980}]

I want to filter it based on the condition that if the parent_id of one object is equal to the orig_id or the parent_id of the other object then keep the first hash and remove the other.

From the above scenario, the second hash will be removed and the output would be:

a = [{'id'=> '1', 'subject'=> 'this is subject 1', 'orig_id'=> 123, 'parent_id'=> 123}, 
     {'id'=> '3', 'subject'=> 'this is subject 3', 'orig_id'=> 789, 'parent_id'=> 980}]
2
  • Suppose a = [{‘parent_id’=>1, ‘user_id’=>2}, {‘parent_id’=>2, ‘user_id’=>3}, {‘parent_id’=>3, ‘user_id’=>1}]. What is the desired return value, and why? Commented Feb 9, 2020 at 15:58
  • This looks like you're retrieving records from a database. If so, you should be using a query to do this; It'd be much faster. Commented Feb 9, 2020 at 18:56

1 Answer 1

1

Group by parent_id and detect the proper one, otherwise return all of grouped hashes.

a.
  group_by { |h| h["parent_id"] }.
  flat_map do |id, hs|
    hs.find { |h| h["orig_id"] == id } || hs
  end
Sign up to request clarification or add additional context in comments.

3 Comments

It is my understanding that if a = [{'parent_id'=>1, 'user_id'=>3}, {'parent_id'=>2, 'user_id'=>1}], [{'parent_id'=>1, 'user_id'=>3}] is to be returned, but you return a. Are we interpreting the question differently?
@CarySwoveland I do not know, but this solution was accepted, so...
The question isn't entirely clear so y'all are guessing what the goal is. Instead, get the question clarified first, then answer.

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.