Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

google apps script - Custom function doesn't work with ArrayFormula

i followed the post https://developers.google.com/apps-script/guides/sheets/functions

function DOUBLE(input) {
    return input * 2;
}

and copied the very simple DOUBLE function into my app-script.

=double(A1)

is working and double my integer in 'A1' But when i filled column A with values, like

A1 = 2
A2 = 3
A3 = 4
....

And in B1 cell, i run

=arrayformula(double(A1:A))

it returned error "Result was not a number", #NUM!

I am not sure what goes wrong. Could any app-script gurus helps?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

How about this answer?

  • For example, when =DOUBLE(A1) is used, the value of input of DOUBLE(input) is retrieved as a number or a string (in your case, it's a number.).
  • For example, when =DOUBLE(A1:B1) is used, the values of input of DOUBLE(input) are retrieved as 2 dimensional array.

It is required to calculate after it confirmed whether input is array. The modification which reflected above is as follows.

From :

return input * 2;

To :

return Array.isArray(input) ? input.map(function(e){return e.map(function(f){return f * 2})}) : input * 2;

Note :

When the above modified sample is written using "if" and "for loop", it becomes as follows.

if (Array.isArray(input)) {
  var result = [];
  for (var i = 0; i < input.length; i++) {
    var temp = [];
    for (var j = 0; j < input[i].length; j++) {
      temp.push(input[i][j] * 2);
    }
    result.push(temp);
  }
  return result;
} else {
  return input * 2;
}

If I misunderstand your question, I'm sorry.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...