Javascript: Multiply and Sum Two Arrays

Other answers are almost certainly more efficient, but just to give you a recursive viewpoint (it's nicer in some other languages). It does assume the two arrays are of equal length as you didn't specify what to do if they're not.

function sumProducts(array1, array2) {
    if(array1.length) 
        return array1.pop() * array2.pop() + sumProducts(array1, array2);

    return 0;
}

Edit:

katspaugh suggested flipping the returns which is ever so slightly more efficient (don't have to ! the length).


var sum = 0;
for(var i=0; i< arr1.length; i++) {
    sum += arr1[i]*arr2[i];
}

var arr1 = [2,3,4,5];
var arr2 = [4,3,3,1];
console.log(arr1.reduce(function(r,a,i){return r+a*arr2[i]},0));
34

This shows the "functional" approach rather than the "imperative" approach for calculating the dot product of two vectors. Functional approach (which tends to be more concise) is preferred in such a simple function implementation as requested by the OP.


var a = [1,2,3,4,5];
var b = [5,4,3,2,1];

a.map(function(x, index){ //here x = a[index]
 return b[index] + x 
});

=>[6,6,6,6,6]

//if you want to add the elements of an array:

a.reduce(function(x, y){
 return x + y
});

=>15

You can read about Array.map here. and Array.reduce here