Home > Back-end >  Iterating through an array inside object inside array in Rails
Iterating through an array inside object inside array in Rails

Time:03-10

I'm trying to iterate through an array inside an object inside an array and get all teachers where the subjects match. Here is the nested array Teacher:

teachers: [
    {name: "Dave", subjects: ["english", "math"]},
    {name: "Jamal", subjects: ["history", "science"]},
    {name: "Brian", subjects: ["science", "gym"]},
    {name: "Sally", subjects: ["math", "history"]}
]

And this is the subjects array:

subjects: ["english", "gym"]

I want to be able to get all teachers that have the subjects "english" and "gym". So basically need to get back an output of:

teachers: [
    {name: "Dave", subjects: ["english", "math"]}, 
    {name: "Brian", subjects: ["science", "gym"]}
]

This is what I've come up with so far but this only renders the first object that contains "english" which is Dave. I realize and return makes it so that it exits the loop but I had to add and return otherwise it would be a doublerender error. The answer is prob a completely different way so any method would be appreciated!

subjects.each do |subject|
        Teacher.all.each do |teach|
          if (teach.subjects).include?(subject) then
            render json: teach and return
          end         
        end
end
teachers: [
    {name: "Dave", subjects: ["english", "math"]}
]

How would I be able to keep the loop going to get back Brian as well?

CodePudding user response:

It sounds like you're looking for any teachers who teach any of the subjects in the subjects array, so:

teachers = [
    {name: "Dave", subjects: ["english", "math"]},
    {name: "Jamal", subjects: ["history", "science"]},
    {name: "Brian", subjects: ["science", "gym"]},
    {name: "Sally", subjects: ["math", "history"]}
]

subjects = ["english", "gym"]

teachers.select do |teacher|
  (subjects & teacher[:subjects]).size > 0
end

The ampersane operator is an intersection between the elements of arrays - the values that are in both, in other words.

  • Related