1

I need to filter an array of items using multiple filter arrays. Output should display only the ones that match all of the selected filters.

for example: Main array contains list of a table

 ID   TypeID   LocationID    Name
 1     2          16          AB
 2     2          22          EF
 3     4          75          PQ
 4     4          40          MN
 5     3          16          AB

And I have three filter arrays:

 TypeFilter = [2, 3]
 LocationFilter = [22, 16] 
 NameFilter = ["AB","MN"]

After applying these filters, output should be an object list of this table:

 ID   TypeID   LocationID    Name
 1     2          16          AB
 5     3          16          AB

Thanks

3
  • Probably you need to do chaining of filter function for every condition Commented Aug 9, 2019 at 18:54
  • 3
    just do an inclusive filter in one pass. no need to chain filters here. arr.filter( item => TypeFilter.includes(item.TypeId) && LocationFilter.includes(item.LocationId) && NameFilter.includes(item.Name) ).. However it would be more efficient to store the filters as objects, this way you dont need to do an includes but rather an O(1) lookup on the object key. Commented Aug 9, 2019 at 18:54
  • It worked. Just one more question, How to ignore a particular filter if its length is 0. for eg: if LocationFilter is empty and I want to exclude it from the the result query. Commented Aug 12, 2019 at 5:27

1 Answer 1

2

Just filter each key by it's correspondent filter:

const result = items.filter(item =>{
    const {TypeId, LocationId, Name} = item
    return TypeFilter.includes(TypeId) && LocationFilter.includes(LocationId) && NameFilter.includes(Name)
})
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot. Just one more question, How to ignore a particular filter if its length is 0. for eg: if LocationFilter is empty and I want to exclude it from the the result query.
Could be something like this: TypeFilter.includes(TypeId) && (!LocationFilter || LocationFilter.includes(LocationId))

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.