AdamM
AdamM

Reputation: 183

Finding element occurring in each array in Rails

I have the following array: items = [[573, 574], [573, 574], [573], [573, 574]]

How to find element which is occurring on each array ? From this array i want to get only "573" Anyone could help me ?

Upvotes: 0

Views: 57

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110755

def appears_in_all(arr)
  arr.reduce(:&)
end

appears_in_all [[573, 574], [573, 574], [573], [573, 574]]           #=> [573]
appears_in_all [[573, 574], [573, 574], [573, 574, 578], [573, 574]] #=> [573, 574]
appears_in_all [[573, 574], [573, 574], [573], [573, 574], [2, 4]]   #=> []

Upvotes: 3

Simple Lime
Simple Lime

Reputation: 11090

You can find the smallest sub array in items (to limit the search set) and then select all the elements from that array that appear in all the other arrays in items:

items.min_by(&:length).select do |element|
  items.all? { |sub_array| sub_array.include?(element) }
end
# => [573]

if it's guaranteed only a single element is in all of them, you can use detect instead of select

Upvotes: 3

aromero
aromero

Reputation: 25761

items.flatten.uniq.select{|x| items.map{|y| y.include? x}.all?}

Upvotes: 1

Related Questions