Search code examples
javascriptexcelsumproduct

how to create a function that works same as microsoft excel sumproduct


I am trying to re-create excel sumproduct function in javascript but I am not fully able to do so as I do not exactly know how does it work for both multiplying sums of arrays and also providing logical results if conditions are passed. I am also looking for a summary to describe it's logic but I can only find ways to use it.

I can do the part that sums the result of array multiplication but I want to include the capability to return logical results when it is passed logical conditions

Here is the code for the multiplication:

var x = function(y, x) { 
 let len=y.length, sum=0; product=0;
 if(y.length==x.length) {
    for(i=0;i<len;i++)  
        {
                product=y[i]*x[i];
                sum+=product;

            }
     return sum;
   }

 else return 0;

}

Solution

  • You can pass a callback function as the first argument of your function

    const SUMPRODUCT = (callback, ar1, ar2) => {
      if(ar1.length !== ar2.length)
        throw new RangeError()
    
      let sum = 0
          
      for(i=0; i<ar1.length; i++){
        if(callback(ar1[i], ar2[i]))
          sum += ar1[i] * ar2[i]
      }
    
      return sum
    }
    
    const x = [-5, 12, -7, 0, 10]
    const y = [50, 2, 120, 87, 14]
    
    console.log(SUMPRODUCT((x, y) => x > 0, x, y))