Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Multiply and Sum Two Arrays

I have two arrays of equal length, and I need to multiply the corresponding (by index) values in each, and sum the results.

For example

var arr1 = [2,3,4,5];
var arr2 = [4,3,3,1];

would result in 34 (4*2+3*3+4*3+5*1).

What's the simplest to read way to write this?

like image 841
CaffGeek Avatar asked Jul 28 '11 21:07

CaffGeek


People also ask

How do you sum two arrays?

The idea is to start traversing both the array simultaneously from the end until we reach the 0th index of either of the array. While traversing each elements of array, add element of both the array and carry from the previous sum. Now store the unit digit of the sum and forward carry for the next index sum.

How do you calculate and return the sum of the numbers in the given array in JavaScript?

To get the sum of an array of numbers:Use the Array. reduce() method to iterate over the array. Set the initial value in the reduce method to 0 . On each iteration, return the sum of the accumulated value and the current number.


1 Answers

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.

like image 141
Buck Avatar answered Oct 08 '22 18:10

Buck