2

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.

3
  • Are "Dog", "Cat" and "fish" the only conditions that will be filtered? Why is there a comma , following .includes()? Commented Feb 13, 2019 at 1:31
  • oh for some reason my code worked but that shouldn't be in there thanks Commented Feb 13, 2019 at 1:33
  • @guest271314 Trailing commas in parameter lists are permitted (style is just rare) Commented Feb 13, 2019 at 1:46

1 Answer 1

3

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)
  ))
));
Sign up to request clarification or add additional context in comments.

2 Comments

so I have a question, the code above doesn't work. When the dog.present is not present it should show cat and fish. But the filter above sets it so that if dog is not present the result outputs only dogs. I think it has something to do with the &&
Oh that makes a lot of sense. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.