PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, November 22, 2022

[FIXED] How to filter a table with programmatically set conditions?

 November 22, 2022     filter, javascript, multiple-conditions     No comments   

Issue

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.


Solution

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


Answered By - gog
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing