- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Finding desired sum of elements in an array in JavaScript

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 −

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

- Related Articles
- Finding three elements with required sum in an array in JavaScript
- Finding sum of alternative elements of the array in JavaScript
- Finding desired numbers in a sorted array in JavaScript
- Finding sum of a range in an array JavaScript
- Finding special kind of elements with in an array in JavaScript
- Finding sum of all unique elements in JavaScript
- Sum of distinct elements of an array in JavaScript
- Finding three desired consecutive numbers in JavaScript
- Finding upper elements in array in JavaScript
- Sum of distinct elements of an array - JavaScript
- Triplet with desired sum in JavaScript
- Finding sum of every nth element of array in JavaScript
- Finding the product of array elements with reduce() in JavaScript
- Finding the rotation of an array in JavaScript
- Finding the mid of an array in JavaScript

Advertisements