0

Given str="GC" I need an output of:
[ [ 'G', 'C' ], [ 'C', 'G' ] ]
My code below seems to run the first if statement, create the first entry for the "G":
[["G" "C"]]
But then when the second iteration ("C"), which runs the else if, it converts both to
[ [ 'C', 'G' ], [ 'C', 'G' ] ]

I don't understand, the values I assign in the first if statement are overwritten, and I don't understand why.

function pairElement(str) {
  let a = []
  let b = []

  for (let i=0; i<str.length;i++) {
    a[i]=b
    if (str[i]=="G") {
      console.log("case 1")
      a[i][0]="G"
      a[i][1]="C"
      console.log(a)
    }
    else if (str[i]=="C") {
      console.log("case 2")
      a[i][0]="C"
      a[i][1]="G"
      console.log(a)
    }
  }

  return a;
}

console.log(pairElement("GC")); //desired output: [ [ 'G', 'C' ], [ 'C', 'G' ] ]

1 Answer 1

1

You create your b value before the loop and that what is cosing the problem: Just create it inside the loop and you should get your desired result.

function pairElement(str) {
  let a = []
  

  for (let i=0; i<str.length;i++) {
	let b = [];
    a[i] = b;
    if (str[i]=="G") {
      console.log("case 1")
      a[i][0]="G"
      a[i][1]="C"
      console.log(a)
    }
    else if (str[i]=="C") {
      console.log("case 2")
      a[i][0]="C"
      a[i][1]="G"
      console.log(a)
    }
  }

  return a;
}

console.log(pairElement("GC"));

Sign up to request clarification or add additional context in comments.

5 Comments

Why is that? I'm looking at it and I don't see 'b' being assigned to a new value within the for loop....so why is it putting it inside fixing things...? I'm missing something still.
Okay I see it is updating b within the for loop..where is it doing this tho...?
When you are creating b outside the loop, you are basicly reassing its values inside the loop. In the first iteration i=0 -> b = ['G','C'], but on the second iteration i=1 yoy are reassigning it to b=['C','G']
Oh nvm I see now....cause its an array the a[i]=b is updating the original b as well cause it's referencing the same data.
Yep, and when b is created inside the loop you are creating new object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.