Filter array by value only if value is defined

How can I peform this filter but only check each condition if the value is not undefined?
For example, if taxId is undefined I want to ignore it instead of filtering by it.

this.subAgencies = demoSubAgencies.filter(function(subAgency) {
  return subAgency.subAgencyName == agencyName
    && subAgency.taxId == taxId
    && subAgency.accountNumber == accountNumber;
});

>Solution :

You can try by dynamically constructing your filter conditions based on the presence of values. You can use the && operator to chain the conditions, but only include a condition if the corresponding value is not undefined.

Here’s an example of how you can do it:

this.subAgencies = demoSubAgencies.filter(function(subAgency) {
  let condition = true; // Start with a true condition

  // Check if agencyName is defined, and if so, include it in the condition
  if (agencyName !== undefined) {
    condition = condition && subAgency.subAgencyName == agencyName;
  }

  // Check if taxId is defined, and if so, include it in the condition
  if (taxId !== undefined) {
    condition = condition && subAgency.taxId == taxId;
  }

  // Check if accountNumber is defined, and if so, include it in the condition
  if (accountNumber !== undefined) {
    condition = condition && subAgency.accountNumber == accountNumber;
  }

  return condition;
});

Leave a Reply