hunter21188
hunter21188

Reputation: 415

Google Apps Script Compare Active User to Array

Not sure why this isn't working. I have a simple script that grabs the active user and checks to see if they are in an array of allowed senders. If they are, then it runs another function sendEmail(). If they are not in the array, then it throws an error.

function send(){
  var ValidEmailsArray = ['[email protected]', '[email protected]', '[email protected]']; //can be any number of emails.
  var ActiveUser = Session.getActiveUser().getEmail();

  for (var i = 0; i < ValidEmailsArray.length; i++){
    if (ActiveUser.indexOf(ValidEmailsArray[i]) == -1) {
      throw new Error('Woah! You must send the email from the ' + ValidEmailsArray + ' account.');
    }
    else {
      sendEmail();
      return;
    }
  }

As it is now, it throws the error even if the ActiveUser is in the ValidEmailsArray.

Any help would be much appreciated. Thanks!

Upvotes: 0

Views: 72

Answers (1)

TheMaster
TheMaster

Reputation: 50445

Issue:

ActiveUser is of type string.

if (ActiveUser.indexOf(ValidEmailsArray[i]) == -1) {throw new Error

says that if ActiveUser doesn't contain the first email address in ValidEmailsArray, throw a error.

Solution:

Use Array#includes instead of a loop.

Snippet:

function send(){
  const validEmailsArray = ['[email protected]', '[email protected]', '[email protected]']; //can be any number of emails.
  const activeUser = Session.getActiveUser().getEmail();
  if(validEmailsArray.includes(activeUser)) sendEmail()
  else throw  new Error("?!")
}

Upvotes: 4

Related Questions