Multiply and Sum Two Arrays in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in two arrays of equal length. The function should multiply the corresponding (by index) values in each, and sum the results.

For example: If the input arrays are −

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

then the output should be 34, because,

(4*2+3*3+4*3+5*1) = 34

Example

The code for this will be −

const arr1 = [2, 3, 4, 5];
const arr2 = [4, 3, 3, 1];
const produceAndAdd = (arr1 = [], arr2 = []) => {
   let sum = 0;
   for(let i=0; i < arr1.length; i++) {
      const product = (arr1[i] * arr2[i]);
      sum += product;
   };
   return sum;
};
console.log(produceAndAdd(arr1, arr2));

Output

And the output in the console will be −

34
raja
Published on 21-Nov-2020 10:01:31
Advertisements