Compare arrays and remove duplicates in Ruby?

What would be the easiest way to compare multiple arrays and remove duplicates?

So (arrays inside arrays in this case) ...

a = [[2, 1], [3, 3], [7, 2], [5, 6]]  
b = [[2, 1], [6, 7], [9, 9], [4, 3]]  
c = [[2, 1], [1, 1], [2, 2], [9, 9]]  
d = [[2, 1], [9, 9], [2, 2], [3, 1]]  

... will exit (with priority given to array a, then b, then c, then d)

a = [[2, 1], [3, 3], [7, 2], [5, 6]]  
b = [[6, 7], [9, 9], [4, 3]]  
c = [[1, 1], [2, 2]]  
d = [[3, 1]]  
+3
source share
2 answers

It is easy to set the difference or subtract, and you can write it down as such. Overloading the operator can be bliss :)

a - this is what it is.

a
[[2, 1], [3, 3], [7, 2], [5, 6]]

b = b - a
[[6, 7], [9, 9], [4, 3]]

c = c - b - a # or c - (a + b)
[[1, 1], [2, 2]]

d = d - c - b - a # or d - (a + b + c)
[[3, 1]]
+13
source

The presence of all arrays in one large array:

a = [[[2, 1], [3, 3], [7, 2], [5, 6]],
[[2, 1], [6, 7], [9, 9], [4, 3]],
[[2, 1], [1, 1], [2, 2], [9, 9]],
[[2, 1], [9, 9], [2, 2], [3, 1]]]

You can achieve what you want:

a.inject([]) do |acc, pairs|
  acc << pairs.uniq.reject{|pair| acc.flatten(1).member?(pair)}
end

Note. I'm not sure which version of Ruby Array#flattenstarted accepting the arguments.

Edit: Anurag, :

a.inject([]) do |acc, pairs|
  acc << (pairs - (acc.inject(&:+) || []))
end
+1

Source: https://habr.com/ru/post/1757192/


All Articles