Why am I getting this problem?

If you apply separate filters in sequence or only check one property at a time your code will match on one criterion and ignore the rest. Beginners often chain .filter() calls or mix &&/|| incorrectly which will miss or include extra results.

Solution

Use a single .filter() call with a combined predicate that tests every property you care about. For dynamic criteria loop over the filter keys and make sure all conditions pass before including an item.

Code Example

// Sample dataconst products = [

  { id: 1, color: ‘red’, size: ‘M’, inStock: true },

  { id: 2, color: ‘blue’, size: ‘L’, inStock: false },

  { id: 3, color: ‘red’, size: ‘S’, inStock: true },

  // …more items…

];

 

// Dynamic filter criteria (could come from form inputs)

const filters = {

  color: ‘red’,

  size: ‘M’,

  inStock: true,

};

 

// Filter in one pass

const filteredProducts = products.filter(product =>

  Object.entries(filters).every(([key, value]) =>

    // Skip empty filters

    value === ” || product[key] === value

  )

);

 

console.log(filteredProducts);

// → [{ id: 1, color: ‘red’, size: ‘M’, inStock: true }]

Also Read: ReactJS Integration Services

How it works

  1. Object.entries(filters) gives [[‘color’,’red’], [‘size’,’M’], [‘inStock’, true]].
  2. .every() makes sure every filter pair matches the corresponding property on the item.
  3. Skips any empty or undefined filter values so you can toggle filters on and off.

Key Takeaways

  • Combine all checks in a single .filter() for correct boolean logic.
  • Use every() to require every criterion to match.
  • Dynamically build your filter object to handle optional fields or form inputs.