Left right subarray sum product - JavaScript


We are required to write a JavaScript function that takes in an array of numbers of length N (N should be even) and divides the array into two sub-array (left and right) containing N/2 elements each and do the sum of the subarrays and then multiply both the subarrays.

For example: If the input array is −

const arr = [1, 2, 3, 4]

Then the output should be −

(2+1) * (3+4)
= 21

Example

Following is the code −

const arr = [1, 2, 3, 4]
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: 0,
         right: 0
   });
   return creds.left * creds.right;
};
console.log(subArrayProduct(arr));

Output

Following is the output in the console −

21

Updated on: 16-Sep-2020

81 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements