Using _.intersection for deep many to many filter

Sometime you might find yourself needing a fast way to do a complex match on property from an array of objects under a property (confused?)

Let’s say I have a collection of objects as such:

I want to have a fast way to get all items that are in group ID: 1 OR 2.  The transverse can be just as useful, items NOT in groups with ID of 1 OR 2.

UnderscoreJS’s intersection┬ámethod in conjunction with _.pluck can make short work of this task.

Here’s an example (in Typescript) for the given array of objects as above (array of objects, with property of ‘groups’, which is an array of group objects)

The key here is the _.filter declaration within the Typescript method wrapper.

 

Leave a Reply

Your email address will not be published. Required fields are marked *