Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete duplicate elements from Array

Tags:

arrays

ruby

I have two arrays, array1 and array2, as follows:

array1 = [ obj11, obj21, obj31 ]
array2 = [ obj21, obj22, obj23 ]

Objects in both arrays are from the same class. I want to check if array1 contains objects that already exist in array2 and delete them.

Let's say obj11 and obj22 are equal. By "equal," I mean they have similar attribute values. Then I would like to delete obj11 from array1, then insert obj21 and obj31 in array2.

I already define equality for attributes in the objects' class from here:

def ==(other)
  return self.a == other.a && self.b == other.b
end

The resulting array would be:

array2 = [ obj21, obj22, obj23, obj21, obj31 ]
like image 986
Arwa Avatar asked Jan 20 '26 16:01

Arwa


1 Answers

You can use Array#| ( it does union operation) to remove duplicates too.

array1 = ["dog", "cat", "had"]
array2 = ["big", "fight", "had"]
array1 | array2
# => ["dog", "cat", "had", "big", "fight"]
like image 172
Arup Rakshit Avatar answered Jan 23 '26 06:01

Arup Rakshit