Home > database >  Filter array with multiple values
Filter array with multiple values

Time:07-08

Let's imagine that I have an array of emails and I want to filter a specific domain, like:

const emails = ['[email protected]', '[email protected]', '[email protected]']
const excludedDomain = '@hotmail';

const eligibleEmails = emails.filter(email => !emails.includes(excludedDomain));
//Works!

What If I want to exclude more than one value?

const emails = ['[email protected]', '[email protected]' '[email protected]']
const excludedDomains = ['@hotmail', '@yahoo'];

const eligibleEmails = ...

I tried to work with some(), but it returns a boolean and I need to return a new filtered array. Tried to mix filter() and some() but didn't work.

CodePudding user response:

Combine filter() with some() and includes() to check if any of the excludedDomains includes() in the current email we're filtering

const emails = ['[email protected]', '[email protected]', '[email protected]']
const excludedDomains = ['@hotmail', '@yahoo'];

const eligibleEmails = emails.filter(e => !excludedDomains.some(ee => e.includes(ee)));
console.log(eligibleEmails);

CodePudding user response:

Just use another filter on excludeDomain inside your original filter.

const emails = ['[email protected]', '[email protected]', '[email protected]'];
const excludedDomains = ['@hotmail', '@yahoo'];

const filtered = emails.filter(email => 
  excludedDomains.filter(ed => email.includes(ed)).length === 0
)

console.log(filtered); // [ '[email protected]' ]
  • Related