Search code examples
javascriptnested-loops

Using a map function instead of a nested loop condition JS


I have the following function which takes in an array of numbers and a target value, if any 2 of the numbers in the array can be added to give the target value, the function returns true, if not it returns false. E.g if array = [5,4,2,3,1] and target = 9, the function should return true as 5+4=9. However if target = 10, the function should return false as no 2 numbers in the array can be added to give 10.

function Solution(array,target) {
    for (var i = 0;i<array.length;i++) {
      for (var j=0;j!=i && j<array.length;j++) {
        if (array[i] + array[j] == target) {
        return true
      }
    }
  }
  return false
}

The above function works as expected however I don't think this is a good way of doing it, can anybody show me a more efficient way using a map function?


Solution

  • You could take a hash table with the needed delta as key.

    This approach needs only one iteration.

    function solution(array, target) {
        const seen = {};
        for (const value of array) {
            if (seen[value]) return true;
            seen[target - value] = true;
        }
        return false;
    }
    
    console.log(solution([5, 4, 3, 2, 1], 9));  //  true
    console.log(solution([5, 4, 3, 2, 1], 10)); // false