Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2D array - How to remove duplicate values but keep the sub arrays separated

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!
like image 644
ZeeZee Avatar asked Dec 13 '22 11:12

ZeeZee


2 Answers

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]]
like image 129
Aleksei Matiushkin Avatar answered Jan 05 '23 00:01

Aleksei Matiushkin


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]]
like image 44
spickermann Avatar answered Jan 05 '23 00:01

spickermann