5

I am trying to loop through an array and filter out all the items that do not match specific values.

For example I have this array:

const emails = ["[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"];

I would like to filter out emails that end in"

*@hotmail.com *@gmail.com


I have given it a go and got this but this doesn't work:

const filtered = emails.filter((email) => {
  return !email.includes('@hotmail.com') || !email.includes('@gmail.com');
});

The preferred output from the example above would be:

["[email protected]", "[email protected]", "[email protected]"]
1
  • What about return !(email.endsWith('@hotmail.com') || email.endsWith('@gmail.com'))? Commented Jan 27, 2017 at 13:00

1 Answer 1

10

Replace the or || with an and &&

If you select all emails which do not contain hotmail OR do not contain gmail, you'll get all of them which don't contain both which isn't your objective.
You want to get all of those that do not contain both hotmail and gmail instead!

const filtered = emails.filter((email) => {
  return !email.includes('@hotmail.com') && !email.includes('@gmail.com');
});
Sign up to request clarification or add additional context in comments.

Comments

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.