Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 do the product of the subarrays and then add both the results thus obtained.
For example, If the input array is −
const arr = [1, 2, 3, 4, 5, 6]
Then the output should be −
(1*2*3) + (4*5*6) 6+120 126
The code for this will be −
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));
Following is the output on console −
126
Advertisements