Check for Partial Match in an Array

后端 未结 5 1255
长情又很酷
长情又很酷 2021-01-26 03:23

I have a JavaScript array that contains some words that cannot be used when requesting user accounts to be created.

I am trying to loop over the accounts requested and c

5条回答
  •  迷失自我
    2021-01-26 03:46

    You probably won't need to use all of this but it should be helpful none the less:

    var blacklist = ["admin", "webform", "spoof"];
    var newAccounts = ["admin1@google.com", "interweb@google.com", "puppy@google.com"];
    var invalidAccounts = [];
    
    // transform each email address to an object of the form:
    // { email: string, valid: boolean }
    var accountObjects = newAccounts.map(function (a) {
        return { email: a, valid: true };
    });
    
    // loop over each account
    accountObjects.forEach(function (account) {
        // loop over the blacklisted terms
        blacklist.forEach(function (blacklisted) {
            // check to see if your account email address contains a black listed term
            // and set the valid property accordingly
            account.valid = account.email.search(blacklisted) === -1;
        });
    });
    
    // filter accountObjects, validAccounts will now contain an array of valid objects
    var validAccounts = accountObjects.filter(function (a) {
        return a.valid;
    });
    
    // back to the original type of a string array
    var validEmailAddresses = validAccounts.map(function (a) {
        return a.email;
    });
    

提交回复
热议问题