Home > other >  How to exit out of ForEach loop once condition is met
How to exit out of ForEach loop once condition is met

Time:05-18

I've created a small script that will generate an email if an employee has attendance issues. I'm using two templates, one if an employee has a "late" infraction and one if there are other infractions not including "lates" (for example, no-call no-show, unexcused call-offs, etc). However, in my forEach loop, I cannot figure out how to exit the loops so I don't get multiple emails. How can I exit the loop once one (1) email has been sent?

function sendEiEmail(){
  var ss = SpreadsheetApp.getActive().getSheetByName('Attendance Narrative Generator');
  var arr = ss.getRange(7, 1, 10, 1).getValues(); //Get all values from sheet
  // Logger.log(arr);
var htmlBodyNoLate = HtmlService.createTemplateFromFile("AttendanceNoLate").evaluate().getContent();
var htmlBodyLate = HtmlService.createTemplateFromFile("AttendanceLate").evaluate().getContent();

  arr.forEach(function(res) {
    if(res == 'Late'){

  MailApp.sendEmail({
    to: Session.getActiveUser().getEmail(),
    subject: `Attendance Infractions Narrative - ${firstName} ${lastName} #${employeeEID}`,
    htmlBody: htmlBodyLate,
  });
 return;

  }else{

 MailApp.sendEmail({
    to: Session.getActiveUser().getEmail(),
    subject: `Attendance Infractions Narrative - ${firstName} ${lastName} #${employeeEID}`,
    htmlBody: htmlBodyNoLate,
  });

}

  });
}

CodePudding user response:

It's impossible to break forEach loop. (unless you want to use exceptions, but it's not recommended) There are two options to solve the problem:

  1. Change the loop type to for, and not forEach, and then use the break statement.
  2. Use a flag to know that the email was sent:

function sendEiEmail() {
    var ss = SpreadsheetApp.getActive().getSheetByName('Attendance Narrative Generator');
    var arr = ss.getRange(7, 1, 10, 1).getValues(); //Get all values from sheet
    var htmlBodyNoLate = HtmlService.createTemplateFromFile("AttendanceNoLate").evaluate().getContent();
    var htmlBodyLate = HtmlService.createTemplateFromFile("AttendanceLate").evaluate().getContent();

    var isEmailSent = false;
    arr.forEach(function (res) {
        if (isEmailSent == false) {
            if (res == 'Late') {
                MailApp.sendEmail({
                    to: Session.getActiveUser().getEmail(),
                    subject: `Attendance Infractions Narrative - ${firstName} ${lastName} #${employeeEID}`,
                    htmlBody: htmlBodyLate,
                });
                isEmailSent = true;
            } else {
                MailApp.sendEmail({
                    to: Session.getActiveUser().getEmail(),
                    subject: `Attendance Infractions Narrative - ${firstName} ${lastName} #${employeeEID}`,
                    htmlBody: htmlBodyNoLate,
                });
                isEmailSent = true;
            }
        }

    });
} 

  • Related