Computer >> Computer tutorials >  >> Programming >> Javascript

Find all pairs that sum to a target value in JavaScript


We are required to write a JavaScript function that takes in an array of numbers as the first argument and a target sum number as the second argument.

The function should return an array of all those pair of numbers from the array that add up to the target sum specified by the second argument.

We will use a map object to check for the pairs and push the desired pairs to a new array.

Example

The code for this will be −

const arr = [7, 0, -4, 5, 2, 3];
const allTwoSum = (arr, target) => {
   const map = {};
   const results = [];
   for (let i = 0; i < arr.length; i++) {
      if (map[arr[i]]) {
         results.push([target − arr[i], arr[i]]);
         continue;
      };
      map[target − arr[i]] = true;
   };
   return results;
};
console.log(allTwoSum(arr, 5));

Output

And the output in the console will be −

[ [ 0, 5 ], [ 2, 3 ] ]