- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Multiply and Sum Two Arrays in JavaScript
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
Advertisements