Skip to content

Cross-sum : Function for summing the product of two arrays. #19

@Marxsal

Description

@Marxsal

A frequent scenario is where you have two arrays (or filter runs) of numbers where you want each element from one array to be multiplied by the corresponding element from the other array, and the resulting product to be summed. This is equivalent in a spreadsheet to multiplying two columns by each other and summing the result.

If there's a way to do this with the current set of functions, then I apologize and would be eager to see how to make that work. In the mean time, I came up with the following code below. Note that I don't have it doing the regression like the Sum function does -- I'm not sure that that ability applies in this case.

Thank you
Mark

function Crosssum(a,b) {
if (a instanceof Array && b instanceof Array ) {
var n = 0;
for (var i = 0; i < a.length; ++i) n += (a[i]*b[i]);
return n;
}
return Coerce.ToNum(a,this);
}

exports.crosssum = Crosssum ;

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions