Is there any more efficient way to code this “2 Sum” Questions Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 &lt; index2. Please note that your returned answers (both index1 and index2 ) are not zero-based. Put both these numbers in order in an array and return the array from your function ( Looking at the function signature will make things clearer ). Note that, if no pair exists, return empty list.

If multiple solutions exist, output the one where index2 is minimum. If there are multiple solutions with the minimum index2, choose the one with minimum index1 out of them.

twoSum : function(A, B){
        var tempA = A;
        var index1 = [];
        var index2 = [];
        var Results = [];

        for(var i = 0; i &lt; A.length - 1; i++){
            var temp = B - A[i];
            for(var j = i; j &lt; A.length - 1; j++){
                if(temp == A[j]){
                    if(j - i &gt; 0){
                        if(j &lt; Results[1] || Results.length == 0){
                            if(A[j] != A[Results[1]-1] &amp;&amp; A[i] != A[Results[0]-1]){
                                Results[0] = i + 1;
                                Results[1] = j + 1; 
                            }
                        }
                    }
                }
            }
        }
        return Results;
    }```
Variables tempA, index1 and index2 seem to be unused.

Since you are only interested in if(j - i &gt; 0){, you can start right there
for (int j  = i + 1; and omit the conditional.

Further the condition if(j &lt; Results[1] || Results.length == 0){ should be flipped around to if(Results.length == 0 || j &lt; Results[1]){ to avoid accessing undefined index.

But actually the variable Results is uselesss because you can return the pair as soon as you find it. Just iterate in the desired directions.

function twoSum(input, targetSum){
  const limit = input.length;
  for(var j = 1; j &lt; limit; ++j){
    var temp = targetSum - input[j];
    for(var i = 0; i &lt; j; ++i){
      if(temp == input[i]){
        return [i + 1, j + 1];
      }
    }
  }
  return [];
}