jyoon006 jyoon006 - 3 months ago 14
Javascript Question

dna pairing, pushing array inside an array

function pair(str) {

var dna = [];
var dnaarr = [];

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

if(str[i].indexOf('G') === 0) {
var a = dna.push('C');
}
if(str[i].indexOf('C') === 0) {
var b = dna.push('G');
}
if(str[i].indexOf('A') === 0) {
var c = dna.push('T');
}
if(str[i].indexOf('T') === 0) {
var d = dna.push('A');
}

}
for(var j = 0; j < str.length; j++) {
var e = dnaarr.push(str[j]);
var f = dnaarr.push(dna[j]);
}

return dnaarr;
}

pair("ATGCG");


When I run this code, it returns

[ 'A', 'T', 'T', 'A', 'G', 'C', 'C', 'G', 'G', 'C' ]


I need it to return

[['A', 'T'], ['T', 'A'], ['G', 'C'], ['C','G'], ['G', 'C']]


Could anyone please help me with this code?

Answer

It was a problem with your array pushes.

function pair(str) {

 
  var dnaarr = [];
  //var dnatot = [];

    for(var i = 0; i < str.length; i++) {
         var dna = [];
dna.push(str[i]); //pushing current str[i]
      if(str[i].indexOf('G') === 0) {
        var a = dna.push('C');
      }
      if(str[i].indexOf('C') === 0) {
        var b = dna.push('G');
      }
      if(str[i].indexOf('A') === 0) {
        var c = dna.push('T');
      }
      if(str[i].indexOf('T') === 0) {
        var d = dna.push('A');
      }
dnaarr.push(dna); //pushing the array dna to the main array dnaarr
    }
   

    return dnaarr;
}

console.log(pair("ATGCG"));

Comments