All possible odd length subarrays JavaScript



We are required to write a JavaScript function that takes in an array of numbers as the first and the only input.

The function picks all possible odd length subarrays from the original array, calculate their sum and return the total sum.

Note that by subarray, we mean a contiguous subsequence of the array and not any possible combination of numbers.

For example - 

If the input array is −

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

Then all possible odd length arrays will be −

[1], [2], [3], [4], [5], [1, 2, 3], [2, 3, 4], [3, 4, 5], [1, 2, 3, 4, 5]

And their total sum will be −

const output = 57

Example

const arr = [1, 2, 3, 4, 5];
const sumArray = (arr = []) => arr.reduce((a, b) => a + b);
const oddSum = (arr = []) => {
   let len = 1;
   let sum = 0;
   const { length } = arr;
   while(len <= length){
      for(let i = 0; i + len <= length; i++){
         sum += sumArray(arr.slice(i, i + len));
      };
      len += 2;
   };
   return sum;
};
console.log(oddSum(arr));

Output

This will produce the following output −

57

Advertisements