DevSa
DevSa

Reputation: 198

How to filter an object list on multiple arrays in react.js?

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

Upvotes: 1

Views: 1909

Answers (1)

Dupocas
Dupocas

Reputation: 21317

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)
})

Upvotes: 2

Related Questions