Home > database >  compare different objects of array with same value in ruby
compare different objects of array with same value in ruby

Time:01-02

I have a usecase, where I have two different array of object which consist of same attributes with different/same values. Ex:

x = [#<User _id: 32864efe, question: "comments", answer: "testing">]
y =  [#<ActionController::Parameters {"question"=>"comments", "answer"=>"testing"} permitted: true>}>]

Now, When I am trying to get the difference between these two objects I am expecting difference to be nil when object consists of same value, however it is returning the below response.

x - y => [#<User _id: 32864efe, question: "comments", answer: "testing">]

In some cases, I may have more than one User object in x object. In that case, it should return the difference.

Can you please suggest how we can handle this. Any help would be appreciated.

CodePudding user response:

Is this what you're looking for?

  def compare_arrays(array1, array2)
  result = []

  # Iterate through each object in array1
  array1.each do |obj1|
    # Check if the object exists in array2
    matching_obj = array2.find { |obj2| obj1 == obj2 }
    # If no matching object was found, add the object to the result array
    result << obj1 unless matching_obj
  end

  result
end

This function iterates through each object in array1 and checks if there is a matching object in array2. If no matching object is found, the object is added to the result array.

You can use this function like this:

array1 = [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }]
array2 = [{ id: 1, name: 'John' }]

result = compare_arrays(array1, array2)
# result is [{ id: 2, name: 'Jane' }]
  • Related