Alan
Alan

Reputation: 2639

Get elements in common from array of arrays

Let's say I have an array like this one:

[
  [1, 2, 3, 4],
  [3, 4, 5, 6],
  [4, 5, 6, 8]
]

I need to get the elements in common between them all. How can I achieve that?

The result should be

 common_elements([[1, 2, 3, 4], [3, 4, 5, 6], [4, 5, 6, 8]]) # => [4]

Upvotes: 1

Views: 97

Answers (2)

z atef
z atef

Reputation: 7679

Here is another way of doing it "manually lol"... You do each to iterate of over the nested arrays [[0],[1],[2]], then you iterate over each nested array and use include ary[pos].include?(x) with AND between all three nested arrays to find intersecting value, It will be slow, but handy if you want to add more conditions .

 user> ary = [ [1,2,3,4], [3,4,5,6], [4,5,6,8] ]
 => [[1, 2, 3, 4], [3, 4, 5, 6], [4, 5, 6, 8]] 

user> ary.each { |f| f.each {|x| 
                 puts "#{x}"  if ary[0].include?(x) && ary[1].include?(x) &&  
                 ary[2].include?(x)  }} 
4
4
4

or simply,

2.1.2 :003 > ary = [ [1,2,3,4], [3,4,5,6], [4,5,6,8] ].inject(:&)
 => [4] 

Upvotes: 0

ndnenkov
ndnenkov

Reputation: 36101

[[1, 2, 3, 4], [3, 4, 5, 6], [4, 5, 6, 8]].reduce(:&) # => [4]

The Array#& method gives you set intersection:

[1, 2, 3] & [2, 3, 4] # => [2, 3]

The Enumerable#reduce method can combine the values in given array using an operation:

[1, 2, 3].reduce(:+) # => 6

Upvotes: 4

Related Questions