Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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:
(2*4 + 3*3 + 4*3 + 5*1) = 8 + 9 + 12 + 5 = 34
Using for Loop
The most straightforward approach uses a for loop to iterate through both arrays simultaneously:
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));
34
Using reduce Method
A more functional approach uses the reduce method for cleaner, more readable code:
const arr1 = [2, 3, 4, 5];
const arr2 = [4, 3, 3, 1];
const multiplyAndSum = (arr1, arr2) => {
return arr1.reduce((sum, val, index) => {
return sum + (val * arr2[index]);
}, 0);
};
console.log(multiplyAndSum(arr1, arr2));
34
Using map and reduce Together
This approach first maps the products, then reduces to get the sum:
const arr1 = [2, 3, 4, 5];
const arr2 = [4, 3, 3, 1];
const multiplyAndSum = (arr1, arr2) => {
return arr1
.map((val, index) => val * arr2[index])
.reduce((sum, product) => sum + product, 0);
};
console.log(multiplyAndSum(arr1, arr2));
console.log("Products:", arr1.map((val, index) => val * arr2[index]));
34 Products: [ 8, 9, 12, 5 ]
Comparison
| Method | Readability | Performance | Use Case |
|---|---|---|---|
| for loop | Good | Fastest | Large arrays, performance critical |
| reduce | Excellent | Good | Functional programming style |
| map + reduce | Good | Slower | When intermediate products are needed |
Conclusion
All methods effectively multiply corresponding array elements and sum the results. Use the for loop for performance-critical code, or reduce for cleaner functional programming style.
Advertisements
