0

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 = ['a@a.com', 'b@b.com', 'c@c.com'];
    
    if (arr !== null && arr.length > 0) {
       const arr2 = arr.filter(e => {
          !e.match(/@b.com/);
       });
       console.log(arr2);
    }
Sandra Schlichting
  • 25,050
  • 33
  • 110
  • 162

2 Answers2

2

You forgot return statement:

const arr = ['a@a.com', 'b@b.com', 'c@c.com'];

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 = ['a@a.com', 'b@b.com', 'c@c.com'];

if (arr !== null && arr.length > 0) {
   const arr2 = arr.filter(e => {
      return !e.includes('@b.com');
   });
   console.log(arr2);
}
KiraLT
  • 2,385
  • 1
  • 24
  • 36
0

You forget the return statement.

const arr = ['a@a.com', 'b@b.com', 'c@c.com'];
const arr2 = arr?.length ? arr.filter((e) => !e.match(/@b.com/)) : [];
console.log(arr2);
Meer Humza
  • 49
  • 1