We are required to write a JavaScript function that takes in an array of numbers as the first argument and a number as the second argument. The function should prepare and return an array of all such triplets (consecutive or nonconsecutive), that add up to the number specified by the second argument.
For example −
If the input array and the number are −
const arr = [4, 2, 0, 1, 2, 6, 8, 3, 2, 5]; const num = 8;
Then the output array should be −
const output = [ [ 2, 2, 4 ], [ 1, 3, 4 ], [ 0, 2, 6 ], [ 1, 2, 5 ] ];
Example
Following is the code −
const arr = [4, 2, 0, 1, 2, 6, 8, 3, 2, 5]; const num = 8; const tripletSum = (arr, num) => { if (arr.length === 3) { if (arr[0]+arr[1]+arr[2] === 0) { return [[arr[0],arr[1],arr[2]]]; }; }; const results = []; const hashMap = {}; for (var i=0; i<arr.length; i++) { for (var j=i+1; j<arr.length; j++) { for (var k=j+1; k<arr.length; k++) { if (arr[i]+arr[j]+arr[k] === num) { if (!hashMap[arr[i]*arr[j]*arr[k]]) { results.push([arr[i],arr[j],arr[k]]); results[results.length-1].sort(); hashMap[arr[i]*arr[j]*arr[k]] = true; } } } } } return results; }; console.log(tripletSum(arr, num));
Output
Following is the console output −
[ [ 2, 2, 4 ], [ 1, 3, 4 ], [ 0, 2, 6 ], [ 1, 2, 5 ] ]