Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading