Custom function not accepting arrays properly

33 Views Asked by At

I am trying to write a custom Apps Script Code.gs function. The function is supposed to accept an array parameter from Google Sheets, do some math with it, and then output the number. I am having trouble getting it to accept the array.

For the function:

function Prodmult(legs){
    return legs.length;
};

When I call in in Google Sheets with =Prodmult({1,2,3}) The cell returns 1

How can I handle the array argument properly? I ultimately want to multiply all the numbers in the array together, which is trivial.

3

There are 3 best solutions below

0
TheMaster On

{1,2,3} translates to [[1,2,3]] in JavaScript. The length of [[1,2,3]] is 1. The length of [[1,2,3]][0] is 3.

{1;2;3} translates to [[1],[2],[3]] in JavaScript. The length of [[1],[2],[3]] is 3. The length of [[1],[2],[3]][0] is 1.

See my answer for a more detailed explanation on arrays.

0
ab.it.gcp On

Try this:

=Prodmult(JOIN(,{1,2,3})

https://support.google.com/docs/answer/3094077?hl=en about JOIN for reference.

0
Lewis Rodgers On

Apps Script interprets Prodmult({1,2,3}) as Prodmult([[1,2,3]]). So your function needs to handle a two-dimensional array.

function Prodmult(legs){
    return legs[0].length;
};