We are required to write a JavaScript function that takes in an array of numbers as the first argument and a single number as the second argument.
The function should pick such elements from the array that when added gives the sum specified by the second argument of the array. The function should return an array of all such subarrays of numbers that when added gives the required sum.
Note that the order is not important and if needed we have the liberty to use one number more than once in order to generate the sum.
For example −
If the input array and the sum are −
const arr = [14, 6, 10]; const sum = 40;
Then the output should be −
const output = [ [ 14, 14, 6, 6 ], [ 14, 6, 10, 10 ], [ 6, 6, 6, 6, 6, 10 ], [ 10, 10, 10, 10 ] ];
Example
const arr = [14, 6, 10]; const sum = 40; const findSum = (arr, sum) => { const res = []; const search = (index, part = []) => { const s = part.reduce((a, b) => a + b, 0); if (s === sum){ res.push(part) }; if (s >= sum || index >= arr.length){ return; }; search(index, part.concat(arr[index])); search(index + 1, part); }; search(0); return res; } console.log(findSum(arr, sum));
Output
This will produce the following output −
[ [ 14, 14, 6, 6 ], [ 14, 6, 10, 10 ], [ 6, 6, 6, 6, 6, 10 ], [ 10, 10, 10, 10 ] ]