For loop exiting too early - help!

For loop exiting too early - help!
0

#1

Hi all, while working on the Tic Tac Toe challenge, I’m writing a nested for loop function that keeps exiting after the first loop.

Basically, the possiblePair function is supposed to sum up the value of any two unique pairs in an array. For example, possiblePair[1, 2, 3] should return [3, 4, 5], i.e. [1+2, 1+4, 2+3].

However, my current function keeps returning just [1] as a result.

Thanks in advance for your help!

 function possiblePair(array) {
    var sum = 0; 
    var allPairs = [];
    if(array.length = 1) {
      sum = array[0];
    allPairs.push(sum);
     return allPairs;}                    
    else if (array.length > 1)
   { for(var i=0; i< array.length - 1; i ++) {
      for(var j=i+1; j<array.length; j ++) {
        sum = array[i]+array[j];
        allPairs.push(sum);
      }
    }
    return allPairs;
  }};
  
  console.log(possiblePair([1, 2, 3]))

#2

I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.


#3

thanks, will do next time!


#4

if(array.length = 1) … should be if(arry.length === 1)


#5

that worked!! thank you so much, John! Can’t believe I overlooked that …