0

I'm trying to filter products by ingredients they DO NOT contain. Non containing ingredient filters are cumulative.

Here's the pipe:

import { Pipe, PipeTransform } from '@angular/core';
import { Product } from '../../models/product';
import { GenericFilter } from '../../store/states/results-filters-state';

@Pipe({
  name: 'filterIngredients'
})
export class FilterIngredientsPipe implements PipeTransform {

  transform(value: Product[] = [], ingrs: GenericFilter[] = []): any {
    const activeIngrs = ingrs.filter((ingr: GenericFilter) => ingr.selected);
    if (!activeIngrs.length) {
      return value;
    }
    return value.filter((product: Product) =>
      activeIngrs.find(ai => product.filters.ingredients.some(a => a.id !== ai.id)) 
      || product.filters.ingredients.length === 0
    );
  }

}

Here's the view:

<app-product-preview *ngFor="let product of (products$ | async) | 
   filterIngredients: (ingredientsFilter$ | async) || []>
</app-product-preview>

Models for reference:

export interface Product {
  filters: Filters;
  ...
}
export interface Filters {
  ingredients: Ingredient[];
  ...
}
export interface Ingredient {
  id: number;
  ...
}

It works when filtering by one ingredient, but then it breaks when having more than one. I know using the some method is the problem here since I just reused code for cumulative containing properties in other pipes but I don't know what to use instead for non containing ones...

cerealex
  • 1,649
  • 4
  • 17
  • 37
  • 1
    what is `product.filters`? Maybe an indication of the structure of `Product` or `ingrs` would help. Do you have a working plunk/fiddle? – joshvito Jan 02 '18 at 15:55
  • Please use right logic for filtering where angular or react. Here is the needed js help https://stackoverflow.com/questions/31831651/javascript-filter-array-multiple-conditions – Gary Jan 02 '18 at 16:39
  • I've updated the question with resumed models. The pipe checks for coincidental ids between the user selected ingredients and the ingredients array inside each product, removing the resultant product from the list in the view. If products don't have any ingredients they are also shown. This is a production web app. It'd be quite difficult to make a plunkr out of this. – cerealex Jan 02 '18 at 16:42

0 Answers0