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
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;
});
I fixed some of the things...
for (var x = 0; x < newAccounts.length; x++) // loop through new accounts
{
// for every account check if there is any match in blacklist array
for (var y = 0; y < blacklist.length; y++)
{
// if there is match do something
if (newAccounts[x].indexOf(blacklist[y]) > -1)
{
alert(newAccounts[x] + " is in the blacklist array");
break;
}
}
}
Here is the fiddle: https://jsfiddle.net/swaprks/n1rkfuzh/
JAVASCRIPT:
// Create our arrays
var blacklist = ["admin", "webform", "spoof"];
var newAccounts = ["admin1@google.com", "interweb@google.com", "puppy@google.com"];
var invalidAccounts = [];
for(var x = 0; x < newAccounts.length; x++){
for(var y = 0; y < blacklist.length; y++){
if( newAccounts[x].indexOf(blacklist[y]) > -1){
alert(blacklist[x] + " is in the blacklist array");
// Push the newAccounts value into the invalidAccounts array since it contains
// a blacklist word.
invalidAccounts.push(newAccounts[x]);
}else{
alert('no matches');
}
}
}
A solution using javascript array native functions:
var invalidAccounts = newAccounts.filter(function(account){ // we need to filter accounts
return blacklist.some(function(word){ // and return those that have any of the words in the text
return account.indexOf(word) != -1
})
});
More info on: Array.filter and Array.some
We need two loops to achieve this: something like below:
// Loop over the blacklist array
for(var j = 0; x < newAccounts.length; j++){
for(var x = 0; x < blacklist.length; x++){
if(newAccounts[j].indexOf(blacklist[x]) > -1){
alert(blacklist[x] + " is in the blacklist array");
// Push the newAccounts value into the invalidAccounts array since it contains a blacklist word.
}else{
alert('no matches');
}
}
}