0

Here arr is array target is any number. I wants to return two numbers of arr. Sum of those number equals to value stored in target.

function twoSum(arr, target) {
       var x= arr.forEach(e=>{
       return arr.forEach(num=>{
          if((e+num)===target){
            return [e,num];
          }
        })
      })
      return x;
    }
VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • Problem is with the return statement inside forEach. The return statement in a forEach acts like break and stops the further iteration. Use for loop instead – Beshambher Chaukhwan Apr 10 '21 at 06:22
  • @BeshambherChaukhwan the `return` statemen in `forEach` does exactly nothing here. – VLAZ Apr 10 '21 at 06:25
  • Wouldn't it return the some array or null on the first iteration? Like for the 0th index the first return would return the inner foreach result being an array or null which would then populate upwards to the outer foreach – Beshambher Chaukhwan Apr 10 '21 at 06:28
  • 1
    @BeshambherChaukhwan "*Wouldn't it return the some array or null on the first iteration?*" 1. it wouldn't go inside the `if` the first iteration 2. `forEach` itself doesn't return anything at all. It always produces `undefined` and ignores the return value of the callback. – VLAZ Apr 10 '21 at 06:31
  • Hmm return in foreach is like`continue;` and not `break;` yeah in that case you are correct. Its doing nothing here – Beshambher Chaukhwan Apr 10 '21 at 06:31

0 Answers0