Home > Net >  javascript sum of two numbers inside an array print index of numbers whoose sum = target
javascript sum of two numbers inside an array print index of numbers whoose sum = target

Time:12-07

[https://drive.google.com/file/d/12qIWazKzBr1yJGpo1z106euXVJMKMwEa/view?usp=sharing][1]i have to find the index of two numbers whoose sum = target[number given as argument] i have tried to solve this through for loop but i am not getting the indexex correctly as if the first two numbers of array are 1,1 and target is set as two i am getting answer as [0,0] but i want [0,1]

let arr = [1,1,8,9,7,22,6]




var twoSum = function(nums, target) {
    for(i=0;i<nums.length;i  ){
        for(j=i 1;j<nums.length;j  )
        if(nums[i]   nums[j]==target){
           
            return [nums.indexOf(nums[i]) , nums.indexOf(nums[j])]
        }

    }
};
console.log(twoSum(arr, 2))
i am expecting output as [0,1]
but i am getting output as [0,0]


  [1]: https://i.stack.imgur.com/n1jo7.png

CodePudding user response:

The indexOf method returns the first occurrence of a particular value. Since you have 1 in both 0 and 1 indexes, It will only return 0 because it is the first occurrence of 1.

enter image description here

CodePudding user response:

let arr = [1, 1, 8, 9, 7, 22, 6];

function twoSum(arr, target) {
  for (let i = 0; i < arr.length; i  ) {
    for (let j = i   1; j < arr.length; j  ) {
      if (arr[i]   arr[j] === target) console.log([i, j]);
    }
  }
}

twoSum(arr, 2);

  • Related