Filter out array for specific multiple keys

Viewed 76

I have an array I need to filter out specific keys, so I cannot loop them through. Currently, I have made them separately for each key that I need:

this.filteredCampaigns = this.allCampaigns.filter(
  (item) => item.status?.includes(translatedStateName)
);
this.filteredCampaigns = this.filteredCampaigns.concat(this.allCampaigns.filter(
  (item) => item.description?.toLowerCase().includes(filteredString)
));
this.filteredCampaigns = this.filteredCampaigns.concat(this.allCampaigns.filter(
  (item) => item.type?.toLowerCase().includes(filteredString))
);
this.filteredCampaigns = this.filteredCampaigns.concat(this.allCampaigns.filter(
  (item) => item.code?.toLowerCase().includes(filteredString))
);

I want to know how to combine/chain above instead of doing separately, as its a lot of repeated code. I have tried:

this.filteredCampaigns = this.filteredCampaigns.concat(this.allCampaigns.filter(
  (item) => item.description?.toLowerCase().includes(filteredString)
    && item.type?.toLowerCase().includes(filteredString)
    && item.code?.toLowerCase().includes(filteredString)
));

But of course does not work. How to do it?

Edit: Thanks for the comments, to combine filters I needed to replace && with ||.

1 Answers

Here's what you're looking for:

this.filteredCampaigns = this.allCampaigns.filter(
    (campaign) => campaign.description?.toLowerCase().includes(filteredString)
        || campaign.type?.toLowerCase().includes(filteredString)
        || campaign.code?.toLowerCase().includes(filteredString)
)

(You didn't need the .concat, either.)

Related