Sandra Schlichting
Sandra Schlichting

Reputation: 25996

How to remove elements from array if not matching?

I am trying to delete all elements that matches @b.com, but it returns an empty array even if I remove the !, which leads me to think, I am doing something competently wrong.

Can someone explain what I am doing wrong?

    const arr = ['[email protected]', '[email protected]', '[email protected]'];
    
    if (arr !== null && arr.length > 0) {
       const arr2 = arr.filter(e => {
          !e.match(/@b.com/);
       });
       console.log(arr2);
    }

Upvotes: 0

Views: 985

Answers (2)

Meer Humza
Meer Humza

Reputation: 59

You forget the return statement.

const arr = ['[email protected]', '[email protected]', '[email protected]'];
const arr2 = arr?.length ? arr.filter((e) => !e.match(/@b.com/)) : [];
console.log(arr2);

Upvotes: 0

KiraLT
KiraLT

Reputation: 2607

You forgot return statement:

const arr = ['[email protected]', '[email protected]', '[email protected]'];

if (arr !== null && arr.length > 0) {
   const arr2 = arr.filter(e => {
      return !e.match(/@b.com/);
   });
   console.log(arr2);
}

One more thing, if you don't match by regex, you can just use string.includes:

const arr = ['[email protected]', '[email protected]', '[email protected]'];

if (arr !== null && arr.length > 0) {
   const arr2 = arr.filter(e => {
      return !e.includes('@b.com');
   });
   console.log(arr2);
}

Upvotes: 2

Related Questions