Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 828
mharris7190 Avatar asked Jun 18 '14 22:06

mharris7190


1 Answers

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!

like image 187
Shalev Shalit Avatar answered Sep 21 '22 10:09

Shalev Shalit