Finding desired sum of elements in an array in JavaScript

JavascriptWeb DevelopmentFront End Technology

Suppose we have an array of Numbers like this −

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

We are required to write a JavaScript function that takes in one such array as the first argument. The second argument will be a number that represents a desired sum, let us call it sum, and the third and the last argument will also be a number that represents the count of numbers that should add up to the desired sum from the array (without repetition of elements), let's call this number num.

The function should finally return the number of all such groups that have the desired sum and length.

Therefore, if it the input values are −

const arr = [1, 2, 1, 3, 2];
const sum = 3;
const num = 2;

Then the output should be −

const output = 2;

because the two groups are 1, 2 and 1, 2

Example

The code for this will be −

 Live Demo

const arr = [1, 2, 1, 3, 2];
const sum = 3;
const num = 2;
const findGroups = (arr = [], sum = 1, num = 1) => {
   let count = 0
   for(let i = 0; i < arr.length; i++){
      let part = arr.slice(0 + i, num + i);
      const partSum = part.reduce((acc, val) => acc + val);
      if(partSum === sum){
         count++;
      };
   };
   return count
};
console.log(findGroups(arr, sum, num));

Output

And the output in the console will be −

2
raja
Published on 24-Feb-2021 10:04:26
Advertisements