Home > Net >  Javascript nested for loop function sumArray(array, n)
Javascript nested for loop function sumArray(array, n)

Time:08-17

I am doing an exercise that goes through some validations and there is one that I have not been able to achieve that is true...

The function receives an array and an integer and the goal is that when adding 2 of the numbers in the array, they must return true if the result is equal to the integer that is received as an argument.

It is not valid to add the same number twice, it is only allowed to add different numbers.

The ones that I still can't pass correctly are these:

array = [2,5,7,10,11,15,20] n = 13

In this case, when adding 2 and 11, the result is equal to 13, so the code should return true.

I tried to nest 2 for loops, which is what they suggest me to solve the exercise...

function sumArray(array, n) {
  for(var i = 0; i < array.length; i  ){
    for(var j = 0; j < array.length; j  ){
      if(i   j === n && i !== j){
        return true;
      }
      else{
        return false;
      }
    }
  }
};

CodePudding user response:

You're adding the indices of an array, not the values of it. For example, let's say we have the array [7,8,9]. Your goal is to add 7 8, 7 9, 8 9, right?

However, this code:

  for(var i = 0; i < array.length; i  ){
    for(var j = 0; j < array.length; j  ){
      if(i   j === n && i !== j){

will instead do 0 0, 0 1, 0 2, 1 0, 1 1, 1 2, 2 0, 2 1, 2 2. This is because you're adding i j rather than the values of the array elements contained at indices i and j. Instead, you want to do array[i] array[j]. This will give you 7 7, 7 8, 7 9, 8 7, 8 8, 8 9, 9 7, 9 8, 9 9.

Bonus tip: if(array[i] array[j] === n && i !== j){ will solve the problem, but there's actually a more efficient way to set up your for loops so that you don't need to have the second conditional.

CodePudding user response:

actually you're just using the indicators of the array length not the array values, so you need to change you're code using values instead of the indecators

here is an example of result when i use the the array[i] array[j] instead of i j

function sumArray(array, n) {
  for(var i = 0; i < array.length; i  ){
    for(var j = 0; j < array.length; j  ){
      if(array[i]   array[j] === n && i !== j){
        console.log(array[i] ' ' array[j] true);
      }
      else{
        console.log(array[i] ' ' array[j] false);
      }
    }
  }
};
array=[1,2,3,4,9,8,11]
sumArray(array, 13)

  • Related