Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accept Arbitrary Number of Arguments in Google Scripts Custom Function?

I'm trying to re-build COUNTIFS as a Google Scripts Custom Function and having trouble with one thing: how do I build a function that accepts an arbitrary number of arguments?

If you use COUNTIFS in google sheets, the inputs look like this:

=COUNTIFS(criteria_range1, criterion1, [criteria_range2, criterion2, ...])

My Google Script can be this:

function COUNTIFS(criteria_range1, criterion1){
    // CountIFS code
}

...but how do I get the optional arguments in my function?

like image 202
bumpkin Avatar asked Oct 29 '14 22:10

bumpkin


People also ask

How do you add multiple arguments in Google Sheets?

To get started, open a Google Sheets spreadsheet and click an empty cell. Type =AND(Argument A, Argument B) and replace each argument with the criteria you want to use. You can use as many arguments as you'd like, but you must have at least one for AND to work. In the example below, we used three arguments.

What is === in Google script?

Strict equality (===): a === b results in true if the value a is equal to value b and their types are also the same.


2 Answers

You can reference the arguments object when the number of arguments passed to a function is variable.

like image 194
AdamL Avatar answered Oct 31 '22 00:10

AdamL


(Example to support AdamL's answer.)

The autocomplete feature for custom functions abuses jsdoc tags somewhat. The "parameter type" which is normally enclosed in braces, e.g. {String}, is used verbatim in the "Example" section of the function's help, while the parameter name is used in the quick-help.

You can take advantage of this to clarify functions with arbitrary parameters, as shown here.

screenshot

Code

/**
 * Calculate the driving distance along a route.
 *
 * @param {"london","manchester","liverpool"}
 *                   route  Comma separated ordered list of two or more map
 *                          waypoints to include in route. First point
 *                          is 'origin', last is 'destination'.
 *
 * @customfunction
 */
function drivingDistance(route) {
  if (arguments.length < 2) throw new Error( "Must have at least 2 waypoints." )
  var origin = arguments[0];
  var destination = arguments[arguments.length-1];
  ...
like image 42
Mogsdad Avatar answered Oct 30 '22 23:10

Mogsdad