Search code examples
angularjsunderscore.jslodashangular-filters

Find all Objects in a Collection with at least one matching property


I have an Array with Objects. In short

    Array =[  
    {id = 1, products='1,2'} //products consist of String with Products Seperates by','
    {id = 2, products='1'}  
    {id = 3, products='3'}  
    {id = 4, products='1,2,3'}
    {id = 5, products='2,3'}
    ...  
    ]
SelectedProd = ['2,3']// consists a String as well seperated by ','

This are all Displayed in a Table. Im writing now a Filter to show only the ones which are selected through a MultipleSelect.
Therefore I want filter all Objects where at least one Product is in products
So my Filter is getting the Objects and the Selected Products

.filter('filterByProd', () => {
          return (objects,prod) => {
            var filtered = [];
            /*
FIlter Array
*/
            return filtered;
          };
        });

If a User Selects Product = '2,3' it shall return me the Objects with the id=1/3/4/5..
As well clearly if nothing selected return all. If possible using lodash but other solutions accepted as well.
The problem I have is the Functions are just listed in lodash Docu and cant read everyone which I need.
At the moment Iam stuck at

.filter('filterByProd', () => {
  return (items,prod) => {
    var filtered = [];
    filtered = _.filter(items,['products',prod]);
    return filtered;
  };
});  

This is giving me out only the exact matches with '2,3' -> Object = id=5 only.
I need something

filtered = findAllWhere(selectedProducts,iterateOverSendObjects(checkProductsOfObjects)+_.ifIsAtLeastOneOfSendProducts))  

Solution

  • You can use lodash's intersection method to get your desired result.

    var a = arr.filter(x => {
        return _.intersection(
                 x.products.split(','), SelectedProd[0].split(',')
               ).length > 0;
    

    Here's a working inline fiddle:

    var arr = [  
        {id : 1, products:'1,2'}, 
        {id : 2, products:'1'},  
        {id: 3, products:'3'},  
        {id : 4, products:'1,2,3'},
        {id : 5, products:'2,3'}];
    
    var SelectedProd = ['2,3'];
    
    var a = arr.filter(x => {
        return _.intersection(
                 x.products.split(','), SelectedProd[0].split(',')).length>0;
    });
    
    console.log(a);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.js"></script>

    Explanation :

    Lodash _.intersection returns intersection of two arrays if it exists, or else returns []. We use a filter to filter only those objects where the intersection is non-empty