lost9123193
lost9123193

Reputation: 11040

Adding a Conditional to a Filter function in Javascript

I have an object array called filteredAnimals that returns the animals which are present in a given filter.

 if (!dog.present) {
    filteredAnimals = filteredAnimals.filter(
      e => !e.animal_type.includes('Dog'),
    );
  }

 if (!cat.present) {
    filteredAnimals = filteredAnimals.filter(
      e => !e.animal_type.includes('Cat'),
    );
  }

 if (!fish.present) {
    filteredAnimals = filteredAnimals.filter(
      e => !e.animal_type.includes('fish'),
    );
  }

Is there a way to combine this in one call? I'm a bit stumped because the call won't be made unless the conditional is met. I was thinking of making a function but I feel there's a better way to do this.

Upvotes: 2

Views: 55

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371203

You can use three conditions:

const finalFilteredAnimals = filteredAnimals.filter(({ animal_type }) => (
  (dog.present || !animal_type.includes('Dog')) &&
  (cat.present || !animal_type.includes('Cat')) &&
  (fish.present || !animal_type.includes('fish'))
));

Note that it would be better if dog, cat, and fish were in a larger object, say animals, so that you could iterate over an array of ['Dog', 'Cat', 'fish'] instead:

const finalFilteredAnimals = filteredAnimals.filter(({ animal_type }) => (
  ['Dog', 'Cat', 'fish'].every(animName => (
    animal[animName].present || !animal_type.includes(animName)
  ))
));

Upvotes: 3

Related Questions