Supporting Arrays In Custom Functions With Multiple Inputs
I have a custom function in my google apps script that takes two variables. I want this function to take two arrays for parameters, but the standard approach of putting 'if input.m
Solution 1:
Issue:
multiply
receives two arguments. Whenmultiply
is provided as a function argument toArray.map
, the first argument will be the element of the array on which map is called and the second argument will be the element's index.
Answer :
- Use map only on the first array
x
and then use elements from the corresponding second arrayy
Snippet:
function multiply(x, y) {
if (x.map) {
return x.map(function(xEl, i) {
yEl = y.map ? y[i] : y; // corresponding y Element
return multiply(xEl, yEl);
});
}
if (y.map) {//used, when y is a array and x is number
return multiply(y, x);
}
return x * y;// default
}
a = [[1],[2]];
b= [[3],[4]];
c= [[5,6],[7,8]];
d= [[1,2],[3,4]];
console.log(JSON.stringify(multiply(a,b)));
console.log(JSON.stringify(multiply(a,5)));
console.log(JSON.stringify(multiply(5,b)));
console.log(JSON.stringify(multiply(c,d)));
console.log(JSON.stringify(multiply(c,2)));
console.log(JSON.stringify(multiply(a,c))); //trims c
console.log(JSON.stringify(multiply(c,a)));//throws error
Post a Comment for "Supporting Arrays In Custom Functions With Multiple Inputs"