Search code examples
javascriptangulartypescriptionic-frameworklodash

Filter array of array within a complex object and return that object


I have tried to write pipe like so:

This is what I need to achieve

the filter will allow any objects(items/ItemModel[]) that don't include selected colors (res/FilterMenuDataModel) to be hidden

selected Colors mean's colorIds array.

 transform(items: ItemModel[]): Observable<ItemModel[]> {
    return this.menuElementsDataService.filterMenuFinalDataChanged$.pipe(
      map((res) => {
        if (!res) {
          return items;
        }

        return filter(items, (i) => 'need your help here';
      })
    );
  }

item.model.ts

export interface ItemModel {
  itemId?: number;
  itemName?: string;
  colorIds?: number[]; // one array is this
}

filter-menu-data-model.ts

export interface FilterMenuDataModel {
 
  colorIds?: number[]; // the other array is this
}

Note: res object has FilterMenuDataModel properties.

I have tried many things/many hours without any luck yet. Do you know how to do that? I have used Lodash here. But Javascript way is also fine hence I can convert it to Lodash later.


Solution

  • I think I understand the aim is to find items which have no colorIds in common with items selected by a filterMenu. Lodash offers intersection(), so the filter predicate can be a test for an empty intersection, as follows...

    const items = [
      { itemId: 0, itemName: 'zero', colorIds: [32, 33, 34] },
      { itemId: 1, itemName: 'one', colorIds: [33, 34, 35] },
      { itemId: 2, itemName: 'two', colorIds: [34, 35, 36] },
    ];
    
    // only item one above does not include colors 32 and 36
    const filterMenuData = { colorIds: [32, 36] };
    
    const hideTheseItems = items.filter(item => {
      return _.intersection(item.colorIds, filterMenuData.colorIds).length === 0;
    });
    console.log(hideTheseItems);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>