# others - ruby - 2维数组如何移除重复的值，但是保持子数组分离

``````
a = [1,2,3,4]

b = [2,3,4,5]

c = [3,4,5,6]

d = [4,5,6,7]

newarray = [[1,2,3,4], [2,3,4,5], [3,4,5,6], [4,5,6,7]]

``````

``````
newarraynoduplicates = [[1,2,3,4], [5], [6], [7]]

``````

``````
[a|b|c|d] => [[1, 2, 3, 4, 5, 6, 7]]

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

``````

``````
newarray.uniq! => nil!

``````

``````
[[1,2,3,4], [2,3,4,5], [3,4,5,6], [4,5,6,7]].

each_with_object([]) { |a, acc| acc << a - acc.flatten }

#⇒ [[1, 2, 3, 4], [5], [6], [7]]

``````

``````
[[1,2,3,4], [2,3,4,5], [3,4,5,6], [4,5,6,7]].

reduce([]) { |acc, a| acc << a - acc.flatten }

#⇒ [[1, 2, 3, 4], [5], [6], [7]]

``````

``````
new_array = [a, b - a, c - b - a, d - c - b - a ]

#=> [[1,2,3,4], [5], [6], [7]]

``````

``````
require 'set'

def doit(arr)

s = Set.new

arr.map { |a| a.select { |e| s.add?(e) } }

end

``````
``````
doit [[1,2,3,4], [2,3,4,5], [3,4,5,6], [4,5,6,7]]

#=> [[1, 2, 3, 4], [5], [6], [7]]

doit [[1,2,2,3,4], [2,3,4,5,3], [3,4,5,6], [4,5,6,7]]

#=> [[1, 2, 3, 4], [5], [6], [7]]

``````

``````
newarray = [[1,2,3,4], [2,3,4,5], [3,4,5,6], [4,5,6,7]]

newarray.map.with_index { |e, i| (e - newarray.reverse[newarray.size - i..].flatten).uniq }

#=> [[1, 2, 3, 4], [5], [6], [7]]

``````

``````
newarray.reverse.then{ |ary| newarray.map.with_index { |e, i| (e - ary[newarray.size - i..].flatten).uniq } }

``````