Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 = ['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);
    }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading