All combinations of sums for array in JavaScript


We are required to write a JavaScript function that takes in an array of Numbers as the first argument and a number, say n as the second argument. The number n will always be less than or equal to the length of the array.

Our function should return an array of the sum of all elements of all the possible subarrays of length n from the original array.

For example, If the input is −

const arr = [2, 6, 4];
const n = 2;

Then the output should be −

const output = [8, 10, 6];

Example

The code for this will be −

const arr = [2, 6, 4];
const n = 2;
const buildCombinations = (arr, num) => {
   const res = [];
   let temp, i, j, max = 1 << arr.length;
   for(i = 0; i < max; i++){
      temp = [];
      for(j = 0; j < arr.length; j++){
         if (i & 1 << j){
            temp.push(arr[j]);
         };
      };
      if(temp.length === num){
         res.push(temp.reduce(function (a, b) { return a + b; }));
      };
   };
   return res;
}
console.log(buildCombinations(arr, n));

Output

The output in the console −

[ 8, 6, 10 ]

Updated on: 10-Oct-2020

717 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements