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

2
  • Does this answer your question? Curly Brackets in Arrow Functions Commented Aug 4, 2022 at 7:22
  • You need to return !e.match(/@b.com/); Commented Aug 4, 2022 at 7:23

2 Answers 2

2

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);
}

Sign up to request clarification or add additional context in comments.

Comments

0

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);

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.