Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two arrays and after regex return unique values

I have two arrays. One with a list of emails and another with a list of strings that when matched, should be rejected.

array1 = [ '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]' ]

array 2 = [ /calendar-notification/i,
  /feedproxy/i,
  /techgig/i,
  /team/i,
  /blog/i,
  /info/i,
  /support/i,
  /admin/i,
  /hello/i,
  /no-reply/i,
  /noreply/i,
  /reply/i,
  /help/i,
  /mailer-daemon/i,
  /googlemail.com/i,
  /mail-noreply/i,
  /alert/i,
  /calendar-notification/i,
  /eBay/i,
  /flipkartletters/i,
  /pinterest/i,
  /dobambam.com/i,
  /notify/i,
  /offers/i,
  /iicicibank/i,
  /indiatimes/i,
  /[email protected]/i,
  /facebookmail/i,
  /message/i,
  /facebookmail.com/i,
  /notification/i,
  /youcanreply/i,
  /jobs/i,
  /news/i,
  /linkedin/i,
  /list/i ]

array2 contains all the invalid emails that I want to reject.

How do I compare these two arrays and remove the invalid emails from array1 such that I get

array3 = [ '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]' ]
like image 232
Naveen Paul Avatar asked Nov 30 '25 22:11

Naveen Paul


1 Answers

You can basically filter them:

var newArray = array1.filter(function (elem) {
    var ok = true
    array2.forEach(function (tester) {
        if (tester.test(elem)) {
            ok = false;
        }
    });
    return ok
});

update

As @torazaburo suggested, using some we can have a much cleaner solution:

var newArray = array1.filter(function (elem) {
    return !array2.some(function (tester) {
        return tester.test(elem)
    });
});
like image 85
Adam Avatar answered Dec 03 '25 14:12

Adam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!