I want to remove duplicates from my 2d array but I need to keep sub-arrays separately.
Arrays:
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]]
want to get the following result:
newarraynoduplicates = [[1,2,3,4], [5], [6], [7]]
I have tried the following things
[a|b|c|d] => [[1, 2, 3, 4, 5, 6, 7]]
[a|b|c|d] => [1, 2, 3, 4, 5, 6, 7]
also tried
newarray.uniq! => nil!
The most generic approach would be:
[[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]]
or
[[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]]
I think you are looking for:
new_array = [a, b - a, c - b - a, d - c - b - a ]
#=> [[1,2,3,4], [5], [6], [7]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With