mharris7190
mharris7190

Reputation: 1374

Find intersection of arrays of hashes by hash value

If I have an 2 arrays of hashes for example:

user1.id
=> 1
user2.id
=> 2

user1.connections = [{id:1234, name: "Darth Vader", belongs_to_id: 1}, {id:5678, name: "Cheese Stevens", belongs_to_id: 1}]

user2.connections = [{id:5678, name: "Cheese Stevens", belongs_to_id: 2}, {id: 9999, "Blanch Albertson", belongs_to_id: 2}]

Then how in Ruby can I find the intersection of these two arrays by the hashes id value?

So that for the above example

intersection = <insert Ruby code here>
=> [{id: 5678, name: "Cheese Stevens"}]

I can't just use intersection = user1.connections & user2.connections because the belongs_to_id is different.

Thanks!

Upvotes: 6

Views: 1999

Answers (1)

Shalev Shalit
Shalev Shalit

Reputation: 1963

simple as that:

user1.connections & user2.connections

if you want only by the id key (other attributes are different)

intersection = user1.connections.map{|oh| oh[:id]} & user2.connections.map{|oh| oh[:id]}
user1.connections.select {|h| intersection.include? h[:id] }

hope it helps!

Upvotes: 5

Related Questions