Prince Abalogu
Prince Abalogu

Reputation: 395

How can i compare 2 different arrays and delete duplicated records that already exist in second array from first array

I have two different arrays and I'm trying to avoid duplicates.

I tried looping through arr1 against looping through arr2 and when there is a match it should delete the value from arr1

def gmail_interviews 
  arr1 = []
  arr2 = []

  arr1 = [{"from"=>"chinedu abalogu <[email protected]>",
    "to"=>"chinedu abalogu <[email protected]>",
    "date"=>"chinedu abalogu <[email protected]>",
    "subject"=>[{"name"=>"From", "value"=>"chinedu abalogu <[email protected]>"}],
    "snippet"=>"interview booked"},
   {"from"=>"chinedu abalogu <[email protected]>",
    "to"=>"chinedu abalogu <[email protected]>",
    "date"=>"chinedu abalogu <[email protected]>",
    "subject"=>[{"name"=>"From", "value"=>"chinedu abalogu <[email protected]>"}],
    "snippet"=>"Interview booked for tomorrow"}]

  arr2 = [{"from"=>"chinedu abalogu <[email protected]>",
    "to"=>"chinedu abalogu <[email protected]>",
    "date"=>"chinedu abalogu <[email protected]>",
    "subject"=>[{"name"=>"From", "value"=>"chinedu abalogu <[email protected]>"}],
    "snippet"=>"interview booked"},
   {"from"=>"chinedu abalogu <[email protected]>",
    "to"=>"chinedu abalogu <[email protected]>",
    "date"=>"chinedu abalogu <[email protected]>",
    "subject"=>[{"name"=>"From", "value"=>"chinedu abalogu <[email protected]>"}],
    "snippet"=>"Interview booked for tomorrow"}]

  arr1.each_with_index do |id, index|
    if !arr2.empty?
      arr2.each_with_index do |i, ind|
        if i == id
          puts "Cant save duplicated message to db\n #{id}"
          arr1.delete_at(index)
        end   
      end 
    end
  end

  render json: arr.as_json

end 

from my code, it loops through arr1 once and twice for arr2 and stops instead of looping twice in both arrays as they both contain 2 values count

Basically it finds duplicate for arr1[0] and deletes after that it does not loop through arr1[1]

the return value should be nil or empty as both arrays have the same values.. please what am i missing?

Upvotes: 1

Views: 54

Answers (1)

mrzasa
mrzasa

Reputation: 23317

What about

arr1 - arr2

?

E.g.:

arr1 = [1,2,3,4]
# => [1, 2, 3, 4]
arr2 = [2,3,10]
# => [2, 3, 10]
arr1 - arr2
# => [1, 4]

Docs

Upvotes: 1

Related Questions