3

I have following two array of hashes. I am trying to remove the record from doctor array hash whose doctor_patient_id doesnt not exist in doctor_patient_id array of patient_and_doctor array of hash.

doctor = [
  { :doctor_patient_id=>"abc",
    :doctor_id=>"d1"
  },
  { :doctor_patient_id=>"def",
    :doctor_id=>"d2"
  },
  { :doctor_patient_id=>"ghi",
    :doctor_id=>"d3"
  }
]

patient_and_doctor = [
  { :patient_id=>"11e8f37477ab7028a66b210b9699def9",
    :doctor_patient_id=>[ "def", "zkj", "cps" ]
  },
  { :patient_id=>"11e8f37481fabfe68630f5da2e22dceb",
    :doctor_patient_id=>[ "uio", "ghi", "jkk" ]
  }
]

expected output is:

doctor = [
      { :doctor_patient_id=>"def",
        :doctor_id=>”d2”
      },
      { :doctor_patient_id=>"ghi",
        :doctor_id=>”d3”
      }
    ]

I tried to do something like below but no luck,

patient_and_doctor.each do |dp|
  data = doctor.map {|d| d[:doctor_patient_id].include? 
   dp[:doctor_patient_id] }
end

How can i achieve this?

1
  • Seems like this would be better served creating a relationship between doctors and patients? Commented Nov 29, 2018 at 12:52

2 Answers 2

4
valid_ids = patient_and_doctor.flat_map { |h| h[:doctor_patient_id] }
# => ["def", "zkj", "cps", "uio", "ghi", "jkk"]

doctor.select { |h| valid_ids.include? h[:doctor_patient_id] }
# => [{:doctor_patient_id=>"def", :doctor_id=>"d2"},
#     {:doctor_patient_id=>"ghi", :doctor_id=>"d3"}]

use select! instead of select if you wish to mutate your doctor array instead of returning a new one.

Sign up to request clarification or add additional context in comments.

3 Comments

Depending on the array sizes it might be worth to wrap valid_ids into a Set. This eliminates duplicates and makes lookups based on value faster (arrays are designed with fast lookup by index). Simply add the line valid_ids = Set.new(valid_ids) between the two current lines. Here is a simple benchmark. Keep in mind that this does produces a bit of overhead and is not worth the trouble for small collections.
Fair point, needs also require 'set' though and it's possible to call .to_set at the end of the first line.
Yep, but the require 'set' shouldn't be needed when running in a Ruby on Rails environment, since most (if not all) stuff from std-lib is included by the framework.
1

Following can get required answer,

doctor.select { |x|  patient_and_doctor.map { |x| x[:doctor_patient_id] }.flatten.include?(x[:doctor_patient_id]) }

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.