javascriptarraysgoogle-apps-scriptgoogle-sheetsgoogle-sheets-custom-function

Can I pass an array into a Google App Script method from a Google Spreadsheet?


Can I pass an array into a Google App Script method from a Google Spreadsheet?

Suppose I have an App Script function that expects a list with two elements (note: this example is just an example so please do not tell me that my problem would be solved if I simply passed each element as a separate argument). How do I call this function from a Google Spreadsheet cell?

I've tried both: '=myFunc([1,2])' and '=myFunc((1,2))' and both give me a Parse Error.


Solution

  • In a spreadsheet formula, you can construct an embedded array using curly braces. Semi-colons are row delimiters; commas (or backslashes in locales that use a comma for the decimal separator) are column delimiters.

    Now when such embedded arrays are passed to Google Apps Script, they are converted to a 2-dimensional Javascript array, just like referenced ranges are.

    So:

    =myFunc({1,2})

    =myFunc({1;2})

    function myFunc(value)
    {
    }
    

    In the first formula, value will be [[1, 2]]. In the second, it will be [[1], [2]].