Left right subarray sum product - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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
raja
Published on 16-Sep-2020 09:23:49
Advertisements