mharris7190
mharris7190

Reputation: 1374

Intersection of 2 arrays of hashes by hash value (such as id)

In my rails app, I have a user model and a linkedin_connection model. Linkedin_connection belongs to user and user has_many linkedin_connections.

What's the best way to create a crossover array of connections between user1 and user2?

============== EDIT ============== EDIT ============== EDIT ==============

I realized that this is sort of a different problem than I originally thought. I have 2 arrays of hashes. Each hash has an id element. How can I find the intersection of two hashes by their ids?

Example

user1.linkedin_connections => [{id: "123xyz", name: "John Doe"}, {id: "789abc", name: "Alexander Supertramp"}]

user2.linkedin_connections => [{id: "456ijk", name: "Darth Vader"}, {id: "123xyz", name: "John Doe"}]

cross_connections => [{id: "123xyz", name: "John Doe"}]

How can I calculate "cross_connections?"

Thanks!

Upvotes: 0

Views: 210

Answers (1)

Daiku
Daiku

Reputation: 1227

What you want is the intersection of the two arrays. In ruby, that's easy, using the & operator:

crossover_connections = user1.linkedin_connections.to_a & user2.linkedin_connections.to_a

Upvotes: 2

Related Questions