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

Updated on: 09-Oct-2020

114 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements