zkldi
zkldi

Reputation: 94

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.map, return input.map(function)" doesn't work with two variables.

I have tried recursing through the inputs, but since there are two in the function, it does not work with both.

this is not the function i am using, but it has the same problem.

function multiply(x,y)
{
    if (x.map){
    return x.map(multiply)
    }
    if (y.map){
    return y.map(multiply)
    }
    return x * y
}

I expect the formula to take two arrays (i.e. A1:A5, B1:B5) and perform the function on each variable -- i.e. returning A1 * B1, A2 * B2 etc.

Upvotes: 0

Views: 362

Answers (1)

TheMaster
TheMaster

Reputation: 50443

Issue:

  • multiply receives two arguments. When multiply is provided as a function argument to Array.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.

Solution:

  • Use map only on the first array x and then use elements from the corresponding second array y

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

References:

Upvotes: 2

Related Questions