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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With