Looking for advice on how to write this better. Source is Google Sheets. I have another few IF ELSE statements so looking to consolidate code.
I also want another condition where if employed == "NO" && school == "NO"
and Postcode does not match those listed it sends a separate email.
Code truncated to best address specific question.
if (status == "" && postcode == "4518" || postcode == "4519" || postcode == "4550" || postcode == "4551" || postcode == "4552" || postcode == "4575" && employed == "NO" && school == "NO") {MailApp.sendEmail(// to email 1}); } else if (status == "" && postcode == "4556" || postcode == "4557" || postcode == "4558" || postcode == "4564" && employed == "NO" && school == "NO") {MailApp.sendEmail(// to email 2 }); }}
I could potentially have a second dataset with two columns, Postcode and Email Address. Where a postcode MATCH is found it sends off to the email address listed in Column B. If no match found and employed == "NO" && school == "NO"
then a fallback email is sent. No idea how to write that nor how to start researching that.
Best Answer
So, a couple things -
- I see a few variables that are common for both conditions; status, employed & school. Perhaps you could put them under a default/primary
IF
condition - Introduce
indexOf
within the data array (refer this)
You could accordingly refactor the code as below -
function myFunction() {var postcode = '4558';var status = 'whatever';var employed = 'foo';var school = 'bar';var postcode1 = ["4518","4519","4550","4551","4552","4575"];var postcode2 = ["4556","4557","4558","4564"];if (status == "" && employed == "NO" && school == "NO") {if(postcode1.indexOf(postcode) !== -1) {Logger.log("email 1");} else if (postcode2.indexOf(postcode) !== -1) {Logger.log("email 2");}}}
Here, postcode1
& postcode2
are simply 2 different data arrays that can also be used using the usual Spreadsheet services.
Hope this helps.