0

I have a huge array with multiple arrays inside it. I'm trying to use an angular pipe to filter it but I can only filter through the first level.

Here's a DEMO

@Pipe({ name: 'myfilter' })
export class MyFilterPipe implements PipeTransform {
transform(users: any[], args): any {
return users.filter(user => user.itemName.toLowerCase().includes(args.toLowerCase()))
}

I need to filter through the entire table and display the results with matches the search text

3
  • in the example you have only one level Commented May 19, 2020 at 16:46
  • You say that you have an array with nested arrays, but in the example it's simply an array of objects, is that what you meant to type? From your link I'm getting the behaviour I'm expecting... could you explain what you mean by only filtering through the first level? Commented May 19, 2020 at 16:48
  • I'm sorry. I updated the example. Commented May 19, 2020 at 16:49

1 Answer 1

1

Your search algorithm seems fine (matching the item name), but you're not searching over the deepest elements in your collection. To do this, you can just translate your list of "users" into something that you do want to search. If you were implementing something like this in the future, utilizing TypeScript types can help you ensure you're extracting the correct content. Here is a poorly written implementation that seems to work for your case.

@Pipe({ name: 'myfilter' })
export class MyFilterPipe implements PipeTransform {
  /**
   * In the future, replacing `any[]` with a type that actually
   * reflects the shape of your data will help you navigate
   * each of the properties.
   */
  transform(users: any[], args): any {
    return users.reduce((coll, top) => {
      // these nested reducers are bad, please don't
      // just copy and paste into your project
      if (top.subItemsList.length > 0) {
        return coll.concat(top.subItemsList.reduce((subColl, sub) => {
          if (sub.items.length > 0) {
            return subColl.concat(sub.items);
          }
          return subColl;
        }, []));
      }
      return coll;
    }, []).filter(user => user.itemName.toLowerCase().includes(args.toLowerCase()));
  }
}

Demo on StackBlitz.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.