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
Subarrays product sum in JavaScript
We are required to write a JavaScript function that takes in an array of numbers of length N such that N is a positive even integer and divides the array into two sub arrays (say, left and right) containing N/2 elements each.
The function should calculate the product of each subarray and then add both the results together.
Example
If the input array is:
const arr = [1, 2, 3, 4, 5, 6]
The calculation would be:
(1*2*3) + (4*5*6) 6 + 120 126
Using Array.reduce() Method
Here's the implementation using the reduce method to calculate products of both subarrays:
const arr = [1, 2, 3, 4, 5, 6];
const subArrayProduct = arr => {
const { length: l } = arr;
const creds = arr.reduce((acc, val, ind) => {
let { left, right } = acc;
if(ind < l/2){
left *= val;
}else{
right *= val;
}
return { left, right };
}, {
left: 1,
right: 1
});
return creds.left + creds.right;
};
console.log(subArrayProduct(arr));
126
Using Array.slice() Method
An alternative approach using array slicing for better readability:
const arr = [1, 2, 3, 4, 5, 6];
const subArrayProductSlice = arr => {
const mid = arr.length / 2;
const leftArray = arr.slice(0, mid);
const rightArray = arr.slice(mid);
const leftProduct = leftArray.reduce((acc, val) => acc * val, 1);
const rightProduct = rightArray.reduce((acc, val) => acc * val, 1);
return leftProduct + rightProduct;
};
console.log(subArrayProductSlice(arr));
126
Testing with Different Arrays
// Test with different arrays console.log(subArrayProduct([2, 4, 6, 8])); // (2*4) + (6*8) = 8 + 48 = 56 console.log(subArrayProduct([1, 1, 1, 1])); // (1*1) + (1*1) = 1 + 1 = 2 console.log(subArrayProduct([5, 2, 3, 4])); // (5*2) + (3*4) = 10 + 12 = 22
56 2 22
How It Works
The function works by:
- Dividing the array into two equal halves at the midpoint (length/2)
- Calculating the product of all elements in the left subarray
- Calculating the product of all elements in the right subarray
- Adding both products together to get the final result
Conclusion
Both approaches effectively solve the problem of calculating subarray products and summing them. The slice method offers better readability, while the reduce method is more memory-efficient as it processes elements in a single pass.
