1

The following should take the input and create a 2D array of letter pairs - [["A", "T"], ["T", "A"], ["C","G"]] but it is currently only returning [["A", "T"], ["T", "A"]], which makes me suspect there is something wrong with my loop logic.

function pair(str) {
var paired = [];
var str = str.split("");

for (i=0; i<str.length; i++) {

var newStr = str.splice(0,1);

  if (newStr[0] === "A") {
   newStr.push("T");
  }
  if (newStr[0] === "T") {
   newStr.push("A");
  }
  if (newStr[0] === "C") {
   newStr.push("G")
  }
  if (newStr[0] === "G") {
   newStr.push("C")
  }

paired.push(newStr);
}
   return paired;
}

pair("ATC");
1
  • when you splice , the array length decreases Commented Oct 15, 2015 at 18:19

2 Answers 2

1

Just to promote thinking functionally for more readable code, consider this way of writing it:

pair={"A":"T","T":"A","C":"G","G":"C"};

"ATC".split("").map(function(letter){return [letter,pair[letter]];})

split makes the string an array (as you already know), and then the array's map method lets you say, for each item in this array, use the function provided on that item to produce a new array.

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

Comments

0

The splice is the problem. What you want is:

var newStr = [str[i]];

You need to index it at the character pointed by the index, and then wrap into [] because you want to treat it as an array.

In your original code, you didn't move forward with your loop at all. Worse, because splice modified the original string, its length changed as well, making the loop run less times than it should.

Comments

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.