How to Filter an array of objects to find the objects that share cross referencing properties

  arrays, javascript, sorting

So say for example I’m making a Social app, and I have a user whom I’m trying to make a group match for

const user = {Name: Stan, location: "Chicago", preferences: {locations: ["New York"]} }

and a collection of people objects like so

const matchPool = 
[{Name: Bob, location: "New York", preferences: {locations: ["Chicago"]} },
 {Name: Susan, location: "Miami", preferences: {locations: ["Chicago", "Miami"]} },
 {Name: Tom, location: "Chicago", preferences: {locations: ["Chicago", "New York"]} },
 {Name: Sally, location: "New York", preferences: {locations: ["Chicago", "LA"]} },
 {Name: Carl, location: "New York", preferences: {locations: ["Detroit", "LA", "Chicago"]} }]

Say I wanted a group with Stan included, How would I go about filtering so that every member of the group has a location that is in the preferences of every other member of the group?

My first thought was to use lodash with a filter like so

const FilteredPeople = _.filter(matchPool, function(matchCandidate) { 
   return user.preferences.locations.indexOf(matchCandidate.location) != -1 &&
          matchCandidate.preferences.locations.indexOf(user.location) != -1
 });

If I add Stan to this group returned we would end up with the following

 [{Name: Stan, location: "Chicago", preferences: {locations: ["New York"]}} 
  {Name: Bob, location: "New York", preferences: {locations: ["Chicago"]}},
  {Name: Sally, location: "New York", preferences: {locations: ["Chicago", "LA"]}},
  {Name: Carl, location: "New York", preferences: {locations: ["Detroit", "LA", "Chicago"]}}]

Notice the issue is that while Stan is an acceptable match for Bob, Sally, and Carl and vice versa, Bob/Sally/Carl are not acceptable matches for each other because none of them have New York as a location preference.

I realize its not possible from this small data set but given I have a large match pool with many people, how would I filter so that ALL people retuned are both compatible with the seed person(Stan) and each other?

Source: Ask Javascript Questions

LEAVE A COMMENT