charnould
charnould

Reputation: 2917

How to filter a table with programmatically set conditions?

I've been looking on the internet but couldn't find a simple 2022-style answer .
Considering the table below:

member color size
dad red L
mom red M
brother green S
mom green L
dad red S
sister violet M

I know how to keep only dad and mom where color is red and size L or M.
In pseudo-code (of course filter might be also a solution):

    const to_keep = []
    table.forEach((row) => {
       if (
           (member === 'dad' || member === 'mom') &&
            color === 'red' &&
           (size === 'L' || size === 'M')) {
           to_keep.push(row)
       }
     }

However, what if conditions are not fixed, stored like this, and columns are numerous...

const filters = [
  {filter: "member", value: ['dad', 'mom']},
  {filter: "color", value: ['red']},
  {filter: "size", value: ['L', 'M']},
 ]

How do you write such a function and set conditions programmatically? Thanks.

EDIT

gog's answer is perfect.
But what if the problem is a bit more complex?

Let say that - in fact - only these filters are authorized:

 const authorized = ['color', 'size']

How can I do to use only these authorized filters and not the one not allowed (aka member)? Thanks.

Upvotes: 0

Views: 85

Answers (1)

gog
gog

Reputation: 11347

Something like

array.filter(item => filters.every(f => f.value.includes(item[f.filter])))

should work.

Regarding your update, you can filter the filters like this:

array
    .filter(item =>
        filters
            .filter(f => 
                authorized.includes(f.filter)
            )
            .every(f =>
                f.value.includes(item[f.filter])
            )
    )

Upvotes: 1

Related Questions