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 = ["nick@hotmail.com", "nick@yahoo.com", "nick@gmail.com", "bob@yahhoo.com", "bob@gmail.com", "boc@test.com"];

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:

["nick@yahoo.com", "bob@yahhoo.com", "boc@test.com"]
user3180997
  • 1,836
  • 3
  • 19
  • 31

1 Answers1

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');
});
Antony
  • 1,253
  • 11
  • 19