/** * Returns true if the value is in the array. * * @param {Array} arr * @param {*} val * @returns {boolean} */functioncheckValIn(arr,val){returnarr.indexOf(val)>-1;}vararr_cvi=[1,2,3,4];Logger.log(checkValIn(arr_cvi,5));// false
Remove Duplicates
/** * Returns an array with no duplicate values. * * @param {Array} arr * @returns {Array} */functionrmDuplicatesFrom(arr){varcheck={};varresult=[];varj=0;for(vari=0;i<arr.length;i++){varitem=arr[i];if(check[item]!==1){check[item]=1;result[j++]=item;}}returnresult;}vararr_rdf=[1,2,3,1,2,3,4,];Logger.log(rmDuplicatesFrom(arr_rdf));// [1, 2, 3, 4]
Remove Empty Elements
/** * Returns an array with no empty elements. * * @param {*} x * @returns {Array} */functionrmEmptyEl(x){return(x!==(undefined||''));}vararr_rev=["a",,"b",,,"c"];Logger.log(arr_rev.filter(rmEmptyEl));// ["a", "b", "c"]
Get Count of Values
/** * Returns an array of objects. Objects have two properties, count and value. * * @param {Array} arr * @property {value} a value found in the array * @property {count} count of the value in the array * @returns {Object[]} */functioncountOfValIn(arr){varresult=[];varcopy=arr.slice(0);for(vari=0;i<arr.length;i++){varmyCount=0;for(varw=0;w<copy.length;w++){if(arr[i]==copy[w]){myCount++;deletecopy[w];}}if(myCount>0){varobj={};obj.value=arr[i];obj.count=myCount;result.push(obj);}}returnresult;}vararr_covi=["a","b","c","a","b","c","a"];Logger.log(countOfValIn(arr_covi));// [{count=3.0, value=a}, {count=2.0, value=b}, {count=2.0, value=c}]
Intersect of Two Arrays
/** * Returns an array of the elements in both arrays. * * @param {Array} arrA * @param {Array} arrB * @returns {Array} */functionintersectOf(arrA,arrB){vara=0;varb=0;varresult=[];while(a<arrA.length&&b<arrB.length){if(arrA[a]<arrB[b]){a++;}elseif(arrA[a]>arrB[b]){b++;}else{result.push(arrA[a]);a++;b++;}}returnresult;}vararrA_io=[1,2,3];vararrB_io=[3,4,5];Logger.log(intersectOf(arrA_io,arrB_io));// [3]
Compare Two Arrays
/** * Returns true if both arrays have the same elements in the same order. * * @param {Array} arrA * @param {Array} arrB * @returns {boolean} */functioncompareArr(arrA,arrB){if(arrA.length!==arrB.length)returnfalse;for(vari=arrA.length;i--;){if(arrA[i]!==arrB[i])returnfalse;}returntrue;}vararrA_ca=[1,2,3,4,5];vararrB_ca=[1,2,3,4,5];vararrC_ca=["a","b","c","d","e"];Logger.log(compareArr(arrA_ca,arrB_ca));// trueLogger.log(compareArr(arrA_ca,arrC_ca));// false
Array as Delimited String
/** * Returns a string of array values. * Elements are separated by a delimiter and a space. * * @param {Array} arr * @param {string} delim * @returns {string} */functiondelimStrFromArr(arr,delim){var_arr=rmDuplicatesFrom(arr).sort();varresult="";for(vari=0;i<_arr.length;i++){result+=_arr[i]+delim+" ";}result=result.slice(0,-2);returnresult;}vararr_da=["[email protected]","[email protected]","[email protected]"];Logger.log(delimStrFromArr(arr_da,","));// "[email protected], [email protected], [email protected]"
Array as Modified Delimited String
/** * Returns a string of array values. * Elements are separated by a delimiter and a space, each followed by a modification. * * @param {Array} arr * @param {string} delim * @param {string} mod Modification to append to each item in the array. * @returns {string} */functiondelimStrFromArrMod(arr,delim,mod){var_arr=rmDuplicatesFrom(arr).sort();varresult="";for(vari=0;i<_arr.length;i++){result+=_arr[i]+mod+delim+" ";}result=result.slice(0,-2);returnresult;}vararr_clfd=["x","z","y"];Logger.log(delimStrFromArrMod(arr_clfd,",","@example.com"));// "[email protected], [email protected], [email protected]"
Two-Dimensional Array
Flatten Two-Dimensional Array
/** * Returns an array containing all values in a two-dimensional array. * * @param {Array[]} twoDArr * @returns {Array} */functionflattenTwoDArr(twoDArr){varresult=twoDArr.reduce(function(a,b){returna.concat(b);});returnresult;}varsheet_fma=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");varval_fma=sheet_fma.getRange("G2:H5").getValues();Logger.log(flattenTwoDArr(val_fma).sort());// [1, 2, 3, 4, 5, 6, 7, 8]
/** * Returns an array of objects sorted by a single property value. * * @param {string} prop * @returns {Object[]} */functiondynSort(prop){varsortOrder=1;if(prop[0]==="-"){sortOrder=-1;prop=prop.substr(1);}returnfunction(a,b){varresult=(a[prop]<b[prop]) ? -1 : (a[prop]>b[prop]) ? 1 : 0;returnresult*sortOrder;};}Logger.log(ex_arrObj.sort(dynSort("a")));// [{a=1.0, b=1.0, c=50.0}, {a=10.0, b=2.0, c=500.0}, {a=1000.0, b=1.0, c=5.0}, {a=10000.0, b=2.0, c=5000.0}]/** * Returns an array of objects sorted by multiple property values. * @param {...string} * @returns {Object[]} */functiondynSortM(){varprops=arguments;returnfunction(obj1,obj2){vari=0,result=0,numberOfProperties=props.length;while(result===0&&i<numberOfProperties){result=dynSort(props[i])(obj1,obj2);i++;}returnresult;};}Logger.log(ex_/rrObj.sort(dynSortM("b","c")));// [{a=1000.0, b=1.0, c=5.0}, {a=1.0, b=1.0, c=50.0}, {a=10.0, b=2.0, c=500.0}, {a=10000.0, b=2.0, c=5000.0}]
Find Object With Unique Property Value
/** * Returns the first object in an array of objects with the key value pair. * * @param {Object[]} arrObj * @param {string} pQuery * @param {string} val * @returns {Object} */functionfindObjIn(arrObj,pQuery,val){for(vari=0;i<arrObj.length;i++){varobj=arrObj[i];for(varpropinobj){if(obj.hasOwnProperty(pQuery)&&prop==pQuery&&obj[prop]==val){returnobj;}}}}Logger.log(findObjIn(ex_arrObj,"a",1000));// {a=1000.0, b=1.0, c=5.0}/** * Returns a value from the first matching object in the array. * * @param {Object[]} arrObj * @param {string} pQuery * @param {string} val * @param {string} pReturn * @returns {*} */functionfindObjValIn(arrObj,pQuery,val,pReturn){for(vari=0;i<arrObj.length;i++){varobj=arrObj[i];for(varpropinobj){if(obj.hasOwnProperty(pQuery)&&prop==pQuery&&obj[prop]==val){returnobj[pReturn];}}}}Logger.log(findObjValIn(ex_arrObj,"c",500,"a"));// 10
Find Earliest or Lastest Object by Timestamp
/** * Returns the object with the oldest Timestamp value. * * @param {Object[]} arrObj * @returns {Object} */functionearliestTS(arrObj){if(arrObj.length>=2){varsorted=arrObj.sort(function(a,b){returnnewDate(a.Timestamp)-newDate(b.Timestamp);});returnsorted[0];}else{returnarrObj[0];}}varsheet_fe=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");vararrObj_fe=arrObjFromRange(sheet_fe,"J1:K4");Logger.log(earliestTS(arrObj_fe));// {Timestamp=Sun Feb 19 19:43:40 GMT-06:00 2017, Multiple Choice=A}/** * Returns the object with the latest Timestamp value. * * @param {Object[]} arrObj * @returns {Object} */functionlatestTS(arrObj){if(arrObj.length>=2){varsorted=arrObj.sort(function(a,b){returnnewDate(b.Timestamp)-newDate(a.Timestamp);});returnsorted[0];}else{returnarrObj[0];}}varsheet_le=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");vararrObj_le=arrObjFromRange(sheet_le,"J1:K4");Logger.log(latestTS(arrObj_le));// {Timestamp=Wed Feb 22 19:45:07 GMT-06:00 2017, Multiple Choice=C}
/** * Returns an object with the values of the argument objects. * If multiple objects have the same property value, the last value set is retained. * @param {...Object} * @returns {Object} */functionmergeObjs(){varobj=arguments[0];for(i=1;i<arguments.length;i++){varsrc=arguments[i];for(varkeyinsrc){if(src.hasOwnProperty(key))obj[key]=src[key];}}returnobj;}varobjA_mo={a: 1,b: 2,c: 3};varobjB_mo={c: 4,d: 5,e: 6,f: 7};Logger.log(mergeObjs(objA_mo,objB_mo));// {a=1.0, b=2.0, c=4.0, d=5.0, e=6.0, f=7.0}
Dates and Times
Formatted Timestamps
/** * Returns a string of today's date formatted "month-day-year". * * @returns {string} */functionfmatD(){varn=newDate();vard=[n.getMonth()+1,n.getDate(),n.getYear()];returnd.join("-");}Logger.log(fmatD());// "4-24-2017"/** * Returns a string of the current time formatted "hour:minute:second". * * @returns {string} */functionfmat24T(){varn=newDate();vart=[n.getHours(),n.getMinutes(),n.getSeconds()];for(vari=1;i<3;i++){if(t[i]<10){t[i]="0"+t[i];}returnt.join(":");}}Logger.log(fmat24T());// "20:43:40"/** * Returns a string of today's date and the current time formatted "month-day-year hour:minute:second AM/PM" * * @returns {string} */functionfmat12DT(){varn=newDate();vard=[n.getMonth()+1,n.getDate(),n.getYear()];vart=[n.getHours(),n.getMinutes(),n.getSeconds()];vars=(t[0]<12) ? "AM" : "PM";t[0]=(t[0]<=12) ? t[0] : t[0]-12;for(vari=1;i<3;i++){if(t[i]<10){t[i]="0"+t[i];}}returnd.join("/")+" "+t.join(":")+" "+s;}Logger.log(fmat12DT());// "4-24-2017 8:43:40 PM"
Date Object from String
/** * Returns a new date object from a string formatted year-month-date. * * @param {string} str * @returns {Date} */functiondateObjectFromString(str){varsplit=str.split("-");varmonths=["January","February","March","April","May","June","July","August","September","October","November","December"];returnnewDate(months[(split[1]-1)]+" "+split[2]+", "+split[0]);}Logger.log(dateObjectFromString("2017-04-24"));// Mon Apr 24 00:00:00 GMT-05:00 2017
Match a Date to a Range
/** * Returns a value associated with a date range. * * @param {Object[]} arrObj * @param {string=new Date()} optDate - Date to match. * @namespace * @property {string} start - Starting date. * @property {string} end - Ending date. * @property {*} value - The value to return for a matching date. * @returns {*} */functionmatchDateRange(arrObj,optDate){vardate=newDate();if(optDate!==undefined){date=newDate(optDate);}for(i=0;i<arrObj.length;i++){varstart=newDate(arrObj[i].start);varend=newDate(arrObj[i].end);if(date>=start&&date<=end){returnarrObj[i].value;}}}varquarterDates=[{start: "08/01/2016",end: "10/28/2016",value: 1},{start: "11/02/2016",end: "01/09/2017",value: 2},{start: "01/15/2017",end: "03/19/2017",value: 3},{start: "03/21/2017",end: "06/15/2017",value: 4},{start: "06/16/2017",end: "07/30/2017",value: "summer vacation"}];Logger.log(matchDateRange(quarterDates));// "summer vacation" (06/25/2017)Logger.log(matchDateRange(quarterDates,"08/02/2016"));// 1
Drive
Folders
Create or Verify Folder Path
// -- Create or Verify Folder Path/** * Returns a folder at the end of a folder path. * The folder is created if it does not exist already. * * @param {string} path * @returns {Folder} */functioncreateVerifyPath(path){varsplit=path.split('/');varfldr;for(i=0;i<split.length;i++){varfi=DriveApp.getRootFolder().getFoldersByName(split[i]);if(i===0){if(!(fi.hasNext())){DriveApp.createFolder(split[i]);fi=DriveApp.getFoldersByName(split[i]);}fldr=fi.next();}elseif(i>=1){fi=fldr.getFoldersByName(split[i]);if(!(fi.hasNext())){fldr.createFolder(split[i]);fi=DriveApp.getFoldersByName(split[i]);}fldr=fi.next();}}returnfldr;}Logger.log(createVerifyPath("google-apps-script-cheat-sheet-demo/folders/A/B/C"));// C
Last Folder in Folder Path
/** * Returns the last folder in a folder path. * * @param path * @returns {Folder} */functionlastFolderIn(path){varfi;varsplit=path.split('/');varfldr;for(i=0;i<split.length;i++){if(i===0){fi=DriveApp.getRootFolder().getFoldersByName(split[i]);if(fi.hasNext()){fldr=fi.next();}}elseif(i>=1){fi=fldr.getFoldersByName(split[i]);if(fi.hasNext()){fldr=fi.next();}}}returnfldr;}// Logger.log(lastFolderIn("google-apps-script-cheat-sheet-demo/folders/A/B")); // B// Logger.log(lastFolderIn("google-apps-script-cheat-sheet-demo/folders/A/B/C/D/E/F/G")); // C
Array of All Folders
All Folders in a Folder
/** * Returns an array of all folders in a folder. * * @param {Folder} fldr * @returns {Folder[]} */functionfoldersIn(fldr){varfi=fldr.getFolders();vararr=[];while(fi.hasNext()){var_fldr=fi.next();arr.push(_fldr);}returnarr;}Logger.log(foldersIn(lastFolderIn("google-apps-script-cheat-sheet-demo/folders/")));// [A]
All Folders at Root
/** * Returns an array of all folders in the root of the user's Drive. * * @returns {Folder[]} */functionrootFolders(){varrf=DriveApp.getRootFolder();varfi=rf.getFolders();vararr=[];while(fi.hasNext()){varfldr=fi.next();arr.push(fldr);}returnarr;}Logger.log(rootFolders());
All Folders in Drive
/** * Returns an array of all folders in the user's Drive. * * @returns {Folder[]} */functionallFolders(){varfi=DriveApp.getFolders();vararr=[];while(fi.hasNext()){varfldr=fi.next();arr.push(fldr);}returnarr;}Logger.log(allFolders());
Array of All Folder Names
/** * Returns an array of folder names. * * @param {Folders[]} * @returns {string[]} */functionfolderNames(fldrs){vararr=[];for(vari=0;i<fldrs.length;i++){varname=fldrs[i].getName();arr.push(name);}returnarr;}vararr_fn=foldersIn(lastFolderIn("google-apps-script-cheat-sheet-demo/folders/A/B"));Logger.log(folderNames(arr_fn));// [C]
Find a Folder
Find a Folder in a Folder
/** * Returns a folder. * * @requires foldersIn() * @requires folderNames() * @requires checkValIn() * @param {Folder} fldr * @param {string} name * @returns {Folder} */functionfindFolderIn(fldr,name){varfldrs=foldersIn(fldr);varnames=folderNames(fldrs);if(checkValIn(names,name)){var_fldr=fldr.getFoldersByName(name).next();return_fldr;}}varfldr_ffi=lastFolderIn("google-apps-script-cheat-sheet-demo/folders");Logger.log(findFolderIn(fldr_ffi,"A"));// A
Find a Folder at Root
/** * Returns a folder at the root of the user's Drive. * * @requires rootFolders() * @requires folderNames() * @requires checkValIn() * @param {string} name * @returns {Folder} */functionfindFolderAtRoot(name){varrf=DriveApp.getRootFolder();varfldrs=rootFolders();varnames=folderNames(fldrs);if(checkValIn(names,name)){varfldr=rf.getFoldersByName(name).next();returnfldr;}}Logger.log(findFolderAtRoot("google-apps-script-cheat-sheet-demo"));// google-apps-script-cheat-sheet-demo
Find a Folder in Drive
/** * Returns the first matching folder in Drive. * * @param {string} name * @returns {Folder} */functionfindFolderInDrive(name){varfi=DriveApp.getFoldersByName(name);while(fi.hasNext()){varfldr=fi.next();returnfldr;}}Logger.log(findFolderInDrive("folders"));// folders
Create or Verify Folders
Create or Verify Folders in a Folder
/** * Returns a folder. * Creates folders within a folder if they don't already exist. * * @requires foldersIn() * @requires folderNames() * @requires checkValIn() * @param {Folder} fldr * @param {string[]} names * @returns {Folder} */functioncreateVerifyFoldersIn(fldr,names){varfldrs=foldersIn(fldr);var_names=folderNames(fldrs);for(i=0;i<names.length;i++){if(!(checkValIn(_names,names[i]))){fldr.createFolder(names[i]);}}returnfldr;}varfldr_cvfi=lastFolderIn("google-apps-script-cheat-sheet-demo/folders");Logger.log(createVerifyFoldersIn(fldr_cvfi,["X","Y","Z"]));// foldersLogger.log(foldersIn(fldr_cvfi));// [A,X,Y,Z]
Create or Verify Folders at Root
/**
* Returns the root folder.
* Creates folders at root if they don't exist already.
*
* @param {string[]} names
* @returns {Folder}
*/
function createVerifyFoldersAtRoot(names) {
var rfs = rootFolders();
var _names = folderNames(rfs);
for (i=0; i < names.length; i++) {
if (!(checkValIn(_names, names[i]))) {
DriveApp.createFolder(names[i]);
}
}
return DriveApp.getRootFolder();
}
Files
Array of All Files
All Files in a Folder
/** * Returns an array of files found at the top level of a folder. * * @param {Folder} fldr * @returns {File[]} */functionfilesIn(fldr){varfi=fldr.getFiles();vararr=[];while(fi.hasNext()){varfile=fi.next();arr.push(file);}returnarr;}varfldr_fin=lastFolderIn("google-apps-script-cheat-sheet-demo/files");Logger.log(filesIn(fldr_fin));// [example-file]
All Files at Root
/** * Returns an array of all files at the root of a user's Drive. * * @returns {File[]} */functionrootFiles(){varrf=DriveApp.getRootFolder();varfi=rf.getFiles();vararr=[];while(fi.hasNext()){varfile=fi.next();arr.push(file);}returnarr;}Logger.log(rootFiles());
All Files in Drive
/** * Returns an array of all files in the user's Drive. * * @returns {File[]} */functionallFiles(){varfi=DriveApp.getFiles();vararr=[];while(fi.hasNext()){varfile=fi.next();arr.push(file);}returnarr;}Logger.log(allFiles());
Array of All File Names
/** * Returns an array of file names. * * @param {File[]} files * @returns {string[]} */functionfileNames(files){vararr=[];for(vari=0;i<files.length;i++){varname=files[i].getName();arr.push(name);}returnarr;}varfldr_fnam=lastFolderIn("google-apps-script-cheat-sheet-demo/files");vararr_fnam=filesIn(fldr_fnam);Logger.log(fileNames(arr_fnam));// [example-file]
Find a File
Find a File in a Folder
/** * Returns a file found at the top level of a folder. * * @requires filesIn() * @requires fileNames() * @requires checkValIn() * @param {Folder} fldr * @param {string} name * @returns {File} */functionfindFileIn(fldr,name){varfiles=filesIn(fldr);varnames=fileNames(files);if(checkValIn(names,name)){varfile=fldr.getFilesByName(name).next();returnfile;}}varfldr_ffi=lastFolderIn("google-apps-script-cheat-sheet-demo/files");Logger.log(findFileIn(fldr_ffi,"example-file"));// example-file
Find a File at Root
/** * Returns a file found at the root of a user's Drive. * * @requires rootFiles() * @requires fileNames() * @requires checkValIn() * @param {string} name * @returns {File} */functionfindFileAtRoot(name){varrf=DriveApp.getRootFolder();varfiles=rootFiles();varnames=fileNames(files);if(checkValIn(names,name)){varfile=rf.getFilesByName(name).next();returnfile;}}
Find a File in Drive
/** * Returns the first matching file found in the user's Drive. * * @param {string} name * @returns {File} */functionfindFileInDrive(name){varfi=DriveApp.getFilesByName(name);while(fi.hasNext()){varfile=fi.next();returnfile;}}Logger.log(findFileInDrive("example-file"));// example-file
Find at File at Path
/** * Returns the file found at the end of a path. * * @param {string} path * @returns {File} */functionfindFileAtPath(path){varfi;varsplit=path.split('/');varfile=split[split.length-1];varfldr;for(i=0;i<split.length-1;i++){if(i===0){fi=DriveApp.getRootFolder().getFoldersByName(split[i]);if(fi.hasNext()){fldr=fi.next();}else{returnnull;}}elseif(i>=1){fi=fldr.getFoldersByName(split[i]);if(fi.hasNext()){fldr=fi.next();}else{returnnull;}}}returnfindFileIn(fldr,file);}Logger.log(findFileAtPath("google-apps-script-cheat-sheet-demo/files/example-file"));
/** * Returns the copied file from its new destination. * * @requires findFileIn() * @param {File} file * @param {Folder} fldr * @returns {File} */functionmoveFile(file,fldr){varname=file.getName();vardest=findFileIn(fldr,name);if(dest===undefined)file.makeCopy(name,fldr);var_file=findFileIn(fldr,name);if(_file!==undefined)file.setTrashed(true);return_file;}varfldr_mf1=lastFolderIn("google-apps-script-cheat-sheet-demo/files/copied");varfile_mf=findFileIn(fldr_mf1,"example-file");varfldr_mf2=createVerifyPath("google-apps-script-cheat-sheet-demo/files/moved");Logger.log(moveFile(file_mf,fldr_mf2));// example-file
Files and Folders
Rename a File or Folder
/** * Returns a renamed file or a folder. * * @param {File || Folder} file_fldr * @param {string} name * @returns {File || Folder} */functionrenameFileFldr(file_fldr,name){file_fldr.setName(name);returnfile_fldr;}varfldr_rf=lastFolderIn("google-apps-script-cheat-sheet-demo/files/moved");varfile_rf=findFileIn(fldr_rf,"example-file");Logger.log(renameFileFldr(file_rf,"modified-example-file"));// modified-example-file
Parent Folder of a File or Folder
/** * Returns the parent folder or a file or a folder. * * @param {File || Folder} file_fldr * @returns {Folder} */functionparentFolderOf(file_fldr){varfi=file_fldr.getParents();returnfi.next();}varfile_pfo=findFileInDrive("example-file");Logger.log(parentFolderOf(file_pfo));// files
/** * Returns an object from a URL. * * @param {string} url * @returns {Object} */functionobjFromUrl(url){varrsp=UrlFetchApp.fetch(url);vardata=rsp.getContentText();returnJSON.parse(data);}varobj_ofu=objFromUrl("https://raw.githubusercontent.com/jcodesmn/google-apps-script-cheat-sheet/dev/example.json");Logger.log(JSON.stringify(obj_ofu));
Object From File
/** * Returns an object from a file in Drive. * * @param {File} file * @returns {Object} */functionobjFromFile(file){vardata=file.getBlob().getDataAsString();returnJSON.parse(data);}varfile_off=findFileAtPath("google-apps-script-cheat-sheet-demo/json/example-json");varobj_off=objFromFile(file_off);Logger.log(JSON.stringify(obj_off));
Object From URL or File
/** * Returns an object from a URL or from a file in Drive. * * @param {string || File} input * @returns {Object} */functionobjFromUrlOrFile(input){varregExp=newRegExp("^(http|https)://");vartest=regExp.test(input);if(test){returnobjFromUrl(input);}else{varfile=findFileAtPath(input);returnobjFromFile(file);}}Logger.log(JSON.stringify(objFromUrlOrFile("https://raw.githubusercontent.com/jcodesmn/google-apps-script-cheat-sheet/dev/example.json")));Logger.log(JSON.stringify(objFromUrlOrFile("google-apps-script-cheat-sheet-demo/json/example-json")));
Sheets
Managing Spreadsheet Files
Create or Verify Spreadsheet
Create or Verify Spreadsheet in a Folder
/** * Returns a spreadsheet. * This creates the spreadsheet if it does not already exist. * * @requires filesIn() * @requires fileNames() * @requires checkValIn * @requires moveFile() * @requires findFileIn() * @requires openFileAsSpreadsheet() * @param {Folder} fldr * @param {string} name * @returns {Spreadsheet} */functioncreateVerifySSIn(fldr,name){varfiles=filesIn(fldr);varnames=fileNames(files);if(!(checkValIn(names,name))){varss=SpreadsheetApp.create(name).getId();varfile=DriveApp.getFileById(ss);moveFile(file,fldr);}returnopenFileAsSpreadsheet(findFileIn(fldr,name));}varfldr_cvssi=createVerifyPath("google-apps-script-cheat-sheet-demo/sheets");Logger.log(createVerifySSIn(fldr_cvssi,"example-sheet"));// example-sheet
Create or Verify Spreadsheet at Root
/** * Returns a spreadsheet. * This creates the spreadsheet if it does not already exist. * * @requires rootFiles() * @requires fileNames() * @requires checkValIn() * @requires findFileAtRoot() * @requires openFileAsSpreadsheet() * @param {string} name * @returns {Spreadsheet} */functioncreateVerifySSAtRoot(name){varfiles=rootFiles();varnames=fileNames(files);if(!(checkValIn(names,name))){varss=SpreadsheetApp.create(name);}returnopenFileAsSpreadsheet(findFileAtRoot(name));}
Id of Active Spreadsheet
/** * Returns the Id of the active spreadsheet. * * @returns {string} */functionssId(){var_id=SpreadsheetApp.getActiveSpreadsheet().getId();return_id;}Logger.log(ssId());
Open File as Spreadsheet
/**
* Returns a spreadsheet.
*
* @param {string}
* @returns {Spreadsheet}
*/
function openFileAsSpreadsheet(file) {
var _id = file.getId();
var _ss = SpreadsheetApp.openById(_id);
return _ss;
}
var fldr_ofas = lastFolderIn("google-apps-script-cheat-sheet-demo/sheets")
var file_ofas = findFileIn(fldr_ofas, "example-sheet");
Logger.log(openFileAsSpreadsheet(file_ofas));
Utility Functions for Sheets
Convert Column Number to a Letter
/** * Returns the column number as a alphabetical column value. * Columns are indexed from 1, not from 0. * "CZ" (104) is the highest supported value. * * @param {number} number * @returns {string} */functionnumCol(number){varnum=number-1,chr;if(num<=25){chr=String.fromCharCode(97+num).toUpperCase();returnchr;}elseif(num>=26&&num<=51){num-=26;chr=String.fromCharCode(97+num).toUpperCase();return"A"+chr;}elseif(num>=52&&num<=77){num-=52;chr=String.fromCharCode(97+num).toUpperCase();return"B"+chr;}elseif(num>=78&&num<=103){num-=78;chr=String.fromCharCode(97+num).toUpperCase();return"C"+chr;}}functionex_nc(){for(vari=1;i<=104;i++){varj=numCol(i);Logger.log(i+" - "+j);}}ex_nc();// 1 - A ... CZ - 104
Convert Column Letter to a Number
/** * Returns an alphabetical column value as a number. * * @param {string} column * @returns {number} */functioncolNum(column){varcol=column.toUpperCase(),chr0,chr1;if(col.length===1){chr0=col.charCodeAt(0)-64;returnchr0;}elseif(col.length===2){chr0=(col.charCodeAt(0)-64)*26;chr1=col.charCodeAt(1)-64;returnchr0+chr1;}}functionex_cn(){for(vari=0;i<=25;i++){varabc=String.fromCharCode(97+i).toUpperCase();Logger.log(abc+" - "+colNum(abc));}for(vari=26;i<=51;i++){varabc="A"+String.fromCharCode(97-26+i).toUpperCase();Logger.log(abc+" - "+colNum(abc));}}ex_cn();// A - 1 ... AZ - 52
Replicating Import Range
/** * Replicating import range in Google Apps Script. * Requires a trigger to function. * importRange : From spreadsheet : On edit * */functionimportRange(){varget=sheet_gs.getRange("A2:A5").getValues();varset=sheet_gs.getRange("B2:B5").setValues(get);}
/** * Returns an array of the sheet names for a spreadsheet. * * @param {Spreadsheet} ss * @returns {string[]} */functionarrSheetNames(ss){varsheets=ss.getSheets();vararr=[];for(vari=0;i<sheets.length;i++){arr.push(sheets[i].getName());}returnarr;}varss_asn=SpreadsheetApp.getActiveSpreadsheet();Logger.log(arrSheetNames(ss_asn));// ["Sheet1", "Sheet2", "Sheet3"]
Object
Object From Range
/** * Returns an object from a range. * The top row of the range is assumed to be the header row. * Values in the header row become the object properties. * * @param {Sheet} sheet * @param {string} a1Notation * @returns {Object} */functionobjFromRange(sheet,a1Notation){varrange=sheet.getRange(a1Notation);varheight=range.getHeight();varwidth=range.getWidth();varvalues=range.getValues();varobj={};for(vari=0;i<values.length;i++){obj[values[i][0]]=values[i][1];}returnobj;}varsheet_ofr=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");Logger.log(objFromRange(sheet_ofr,"D2:E5"));// {A=Alpha, B=Bravo, C=Charlie, D=Delta}
Array of Objects
Utility Functions for Array of Objects
Header Values
/** * Returns an array of values for the top row of a range object. * * @param {Range} rangeObj * @returns {Array} */functionheaderVal(rangeObj){varvals=rangeObj.getValues();vararr=[];for(vari=0;i<vals[0].length;i++){varval=vals[0][i];arr.push(val);}returnarr;}varsheet_hv=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");varrange_hv=sheet_hv.getRange("A2:E19");Logger.log(headerVal(range_hv));// ["First", "Last", "Grade", "Homeroom", "Email"]
/** * Returns an array containing all values in the first column of a range. * * @param {Range} rangeObj * @returns {Array} */functionarrForColRange(rangeObj){varheight=rangeObj.getHeight();varvals=rangeObj.getValues();vararr=[];for(vari=0;i<height;i++){arr.push(vals[i][0]);}returnarr;}varsheet_vafro=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");varrange_vafro=sheet_vafro.getRange("A2:F5");Logger.log(arrForColRange(range_vafro));// ["A", "B", "C", "D"]
Docs
Managing Document Files
Create or Verify Document
Create or Verify Document in a Folder
// --- Create or Verify Document in a Folder/** * Returns a document. * This creates the document if it does not already exist. * * @param {Folder} fldr * @param {string} name * @returns {Document} */functioncreateVerifyDocIn(fldr,name){varfiles=filesIn(fldr);varnames=fileNames(files);if(!(checkValIn(names,name))){vardoc=DocumentApp.create(name).getId();varfile=DriveApp.getFileById(doc);moveFile(file,fldr);}returnopenFileAsDocument(findFileIn(fldr,name));}varfldr_cvdi=createVerifyPath("google-apps-script-cheat-sheet-demo/docs");Logger.log(createVerifyDocIn(fldr_cvdi,"example-doc"));// example-doc
Create or Verify Document at Root
/** * Returns a document. * This creates the document if it does not already exist. * * @param {string} name * @returns {Document} */functioncreateVerifyDocAtRoot(name){varfiles=rootFiles();varnames=fileNames(files);if(!(checkValIn(names,name))){varss=DocumentApp.create(name);}returnfindFileAtRoot(name);}
Id of Active Document
/** * Returns the Id of the active document. * * @returns {string} */functiondocId(){var_id=DocumentApp.getActiveDocument().getId();return_id;}
Open File as Document
/** * Returns a file as a document. * * @param {File} file * @returns {Document} */functionopenFileAsDocument(file){var_id=file.getId();var_doc=DocumentApp.openById(_id);return_doc;}varfldr_ofad=lastFolderIn("google-apps-script-cheat-sheet-demo/docs");varfile_ofad=findFileIn(fldr_ofad,"example-doc");Logger.log(openFileAsDocument(file_ofad));
/** * Returns a string. * Words wrapped by the delimiter are replaced with the matching property value. * * @param {Object} obj * @param {string} str * @param {string} delim * @returns {string} */functionstrFromProp(obj,str,delim){varsplit=str.split(" ");varresult=[];for(vari=0;i<split.length;i++){var_str=split[i];for(varpropinobj){varfirst=_str.slice().charAt(0);varlast=_str.slice().substr(-1);varmod=_str.substr(0,_str.length-1).substr(1);if((obj.hasOwnProperty(mod))&&(first===delim)&&(last===delim)){result.push(obj[mod]);}else{result.push(_str);}break;}}returnresult.join(" ");}Logger.log(strFromProp(ex_obj,"name: %name% - state: %state% - job: %job%","%"));// "name: Jon - state: MN - job: IT Administrator"
Replace Object Properties
Replace Object Properties in Document
/** * Words wrapped by the delimiter are replaced with the matching property value. * * @param {Object} obj * @param {Document} doc * @param {string} delim */functionfindReplaceInDoc(obj,doc,delim){varbody=doc.getBody();for(varpropinobj){varquery=delim+prop+delim;varval=obj[prop];body.replaceText(query,val);}}varfldr_frid=createVerifyPath("google-apps-script-cheat-sheet-demo/merges");vardoc_frid=createVerifyDocIn(fldr_frid,"find-replace-doc");varbody_frid=doc_frid.getBody();body_frid.clear();doc_frid.appendParagraph("name: %name%");doc_frid.appendParagraph("state: %state%");doc_frid.appendParagraph("job: %job%");findReplaceInDoc(ex_obj,doc_frid,"%");
Replace Object Properties in Spreadsheet
/** * Words wrapped by the delimiter are replaced with the matching property value. * * @param {Object} obj * @param {Spreadsheet} ss * @param {string} delim */functionfindReplaceInSpreadsheet(obj,ss,delim){varnumSheets=ss.getNumSheets();varsheets=ss.getSheets();for(vari=0;i<numSheets;i++){varsheet=sheets[i];varvalues=sheet.getDataRange().getValues();for(varrowinvalues){varupdate=values[row].map(function(original){vartext=original.toString();for(varpropinobj){varquery=delim+prop+delim;if(text.indexOf(query)!==-1){text=text.replace(query,obj[prop]);}}returntext;});values[row]=update;}sheet.getDataRange().setValues(values);}}varfldr_fris=createVerifyPath("google-apps-script-cheat-sheet-demo/merges");varss_frid=createVerifySSIn(fldr_fris,"find-replace-sheet");varsheet_frid=ss_frid.getSheets()[0];sheet_frid.clear();varval_frid=[["name","state","job"],["%name%","%state%","%job%"]];varrange_frid=sheet_frid.getRange("A1:C2");range_frid.setValues(val_frid);findReplaceInSpreadsheet(ex_obj,ss_frid,"%");
Replace Object Properties in Sheet
/** * Words wrapped by the delimiter are replaced with the matching property value. * * @param {Object} obj * @param {Sheet} sheet * @param {string} delim */functionfindReplaceinSheet(obj,sheet,delim){varvalues=sheet.getDataRange().getValues();for(varrowinvalues){varupdate=values[row].map(function(original){vartext=original.toString();for(varpropinobj){varquery=delim+prop+delim;if(text.indexOf(query)!==-1){text=text.replace(query,obj[prop]);}}returntext;});values[row]=update;}sheet.getDataRange().setValues(values);}varfldr_fris=createVerifyPath("google-apps-script-cheat-sheet-demo/merges");varss_fris=createVerifySSIn(fldr_fris,"find-replace-sheet");varsheet_fris=ss_fris.getSheets()[0];sheet_fris.clear();varval_fris=[["name","state","job"],["<<name>>","<<state>>","<<job>>"]];varrange_fris=sheet_fris.getRange("A1:C2");range_fris.setValues(val_fris);findReplaceinSheet(ex_obj,sheet_fris,"%");
Copy Template for Item in Array of Objects and Replace Object Properties
Copy Document Template and Replace Object Properties
/** * For each object, create a new template document and merge in object values. * * @requires strFromProp() * @requires copyFile() * @requires findReplaceInDoc() * @param {Object[]} arrObj * @param {Document} templateDoc * @param {string} naming * @param {Folder} fldr * @param {boolean} ts * @param {string} delim */functioncreateDocsFromTemplateArrObj(arrObj,templateDoc,naming,fldr,ts,delim){for(vari=0;i<arrObj.length;i++){varobj=arrObj[i];varname=strFromProp(obj,naming,delim);if(ts===true)name+=" - "+fmat12DT();varfile=DriveApp.getFileById(templateDoc.getId());vardocId=copyFile(file,fldr).setName(name).getId();vardoc=DocumentApp.openById(docId);findReplaceInDoc(obj,doc,delim);}}varsheet_cdftao=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");vararrObj_cdftao=arrObjFromSheet(sheet_cdftao,2);varfldr1_cdftao=createVerifyPath("google-apps-script-cheat-sheet-demo/merges");varfldr2_cdftao=createVerifyPath("google-apps-script-cheat-sheet-demo/merges/arrObj-docs");vardoc_cdftao=createVerifyDocIn(fldr1_cdftao,"template-doc");varbody_cdftao=doc_cdftao.getBody();body_cdftao.clear();doc_cdftao.appendParagraph("First: %First%");doc_cdftao.appendParagraph("Last: %Last%");doc_cdftao.appendParagraph("Grade: %Grade%");doc_cdftao.appendParagraph("Homeroom: %Homeroom%");doc_cdftao.appendParagraph("Email: %Email%");createDocsFromTemplateArrObj(arrObj_cdftao,doc_cdftao,"Name: %Last% %First%",fldr2_cdftao,true,"%");
Copy Spreadsheet Template and Replace Object Properties
/** * For each object, create a new template spreadsheet and merge in object values. * * @requires strFromProp() * @requires copyFile() * @requires findReplaceInSpreadsheet() * @param {Object[]} arrObj * @param {Spreadsheet} templateDoc * @param {string} naming * @param {Folder} fldr * @param {boolean} ts * @param {string} delim */functioncreateSpreadsheetsFromTemplateArrObj(arrObj,templateSS,naming,fldr,ts,delim){for(vari=0;i<arrObj.length;i++){varobj=arrObj[i];varname=strFromProp(obj,naming,delim);if(ts===true)name+=" - "+fmat12DT();varfile=DriveApp.getFileById(templateSS.getId());varssId=copyFile(file,fldr).setName(name).getId();varss=SpreadsheetApp.openById(ssId);findReplaceInSpreadsheet(obj,ss,delim);}}varss1_csftao=SpreadsheetApp.getActiveSpreadsheet();varsheet1_csftao=ss1_csftao.getSheetByName("Sheet2");vararrObj_csftao=arrObjFromSheet(sheet1_csftao,2);varfldr1_csftao=createVerifyPath("google-apps-script-cheat-sheet-demo/merges");varfldr2_csftao=createVerifyPath("google-apps-script-cheat-sheet-demo/merges/arrObj-sheets");varfile_csftao=createVerifySSIn(fldr1_csftao,"template-sheet");varss2_csftao=openFileAsSpreadsheet(file_csftao);varsheet2_csftao=ss2_csftao.getSheets()[0];varval_csftao=[["First","Last","Grade","Homeroom","Email"],["%First%","%Last%","%Grade%","%Homeroom%","%Email%"]];varrange_csftao=sheet2_csftao.getRange("A1:E2");range_csftao.setValues(val_csftao);createSpreadsheetsFromTemplateArrObj(arrObj_csftao,file_csftao,"Name: %Last% %First%",fldr2_csftao,true,"%");
Create Bulleted List in Document for Array of Objects
varsheet_mdl=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");vararrObj_mdl=arrObjFromSheet(sheet_mdl,2);varfldr_mdl=createVerifyPath("google-apps-script-cheat-sheet-demo/docs");varfile_mdl=createVerifyDocIn(fldr_mdl,"example-doc");vardoc_mdl=openFileAsDocument(file_mdl);varbody_mdl=doc_mdl.getBody();(function(){arrObj_mdl.sort(dynSortM("Homeroom","Last","First"));varsectionHeader=body_mdl.appendParagraph("Homerooms and Students");sectionHeader.setHeading(DocumentApp.ParagraphHeading.HEADING1);varhomeroom=arrObj_mdl[0]["Homeroom"];body_mdl.appendListItem(homeroom);for(variinarrObj_mdl){if(arrObj_mdl[i]["Homeroom"]===homeroom){body_mdl.appendListItem(arrObj_mdl[i]["First"]+" "+arrObj_mdl[i]["Last"]).setNestingLevel(1).setIndentStart(10).setGlyphType(DocumentApp.GlyphType.HOLLOW_BULLET);}else{homeroom=arrObj_mdl[i]["Homeroom"];body_mdl.appendListItem(homeroom);body_mdl.appendListItem(arrObj_mdl[i]["First"]+" "+arrObj_mdl[i]["Last"]).setNestingLevel(1).setIndentStart(10).setGlyphType(DocumentApp.GlyphType.HOLLOW_BULLET);}}})();
Gmail
Mail Merge
Append Subject and Body Properties for Array of Objects
/** * Returns an array of objects. Subject and Body properties are appended to each object. * * @param {Object[]} arrObj * @param {string} subj * @param {string} body * @param {string} delim * @returns {Object[]} */functionappendSubjBodyForArrObj(arrObj,subj,body,delim){for(vari=0;i<arrObj.length;i++){varobj=arrObj[i];for(varpropinobj){varsearch=delim+prop+delim;if(body.indexOf(search)!==-1){body=body.replace(search,obj[prop]);}if(subj.indexOf(search)!==-1){subj=subj.replace(search,obj[prop]);}}obj.Subject=subj;obj.Body=body;}returnarrObj;}varsheet_aasbfao=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");vararrObj_asbfao=arrObjFromSheet(sheet_aasbfao,2);varsubj_asbfao="Classroom update for %First% %Last%";varbody_asbfao="<p>%First% %Last% is in %Homeroom%'s this fall!</p>";Logger.log(appendSubjBodyForArrObj(arrObj_asbfao,subj_asbfao,body_asbfao,"%"));// [{Last=Garret, [email protected], Homeroom=Muhsina, Grade=6.0, First=Arienne, Body=<p>Arienne Garret is in Muhsina's this fall!</p>, Subject=Classroom update for Arienne Garret}...]
Run Mail Merge for Array of Objects
/** * Sends and email for each object in an array of objects. * Properties Email, Subject and Body are used. * * @requires appendSubjBodyForArrObj() * @param {Object[]} arrObj */functionrunMailMergeForArrObj(arrObj){for(vari=0;i<arrObj.length;i++){varobj=arrObj[i];MailApp.sendEmail({to: obj.Email,subject: obj.Subject,htmlBody: obj.Body});}}varsheet_rmmfao=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");vararrObj_rmmfao=arrObjFromSheet(sheet_rmmfao,2);varsubj_rmmfao="Classroom update for %First% %Last%";varbody_rmmfao="<p>%First% %Last% is in %Homeroom%'s this fall!</p>";arrObj_rmmfao=appendSubjBodyForArrObj(arrObj_rmmfao,subj_rmmfao,body_rmmfao);runMailMergeForArrObj(arrObj_rmmfao);