- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
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 ]
Advertisements