Sean T
Sean T

Reputation: 51

Getting an array result not in order

function pairElement(str) {
    var arr = [['G','C'],['C','G'],['A','T'],['T','A']],b=[]
    for(var k=0;k<arr.length;++k){
        var res = arr.filter(function(v){

            return v;

        })[k][0]
        var j=0;
        while(j<str.length){

            if(str[j]===res){

                b.push(arr[k])
            }
            j++;
        }
    }
    return b;
}

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

I want pairing result in order of the argument passed to the main function. This code's result should be [['A','T'],['T','A'],['C','G'],['G','C'],['A','T']] but i'm getting as [['G','C'],['C','G'],['A','T'],['A','T'],['T','A']]

Upvotes: 0

Views: 49

Answers (1)

castletheperson
castletheperson

Reputation: 33486

Your inner and outer loops are flipped. The outer loop should iterate over the string, and the inner loop should iterate over the array.

function pairElement(str) {
  var arr = [['G', 'C'], ['C', 'G'], ['A', 'T'], ['T', 'A']],
      b = [];
  for (var k = 0; k < str.length; k++) {
    for (var j = 0; j < arr.length; j++) {
      if (str[k] === arr[j][0]) {
        b.push(arr[j]);
      }
    }
  }
  return b;
}

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

Your code can also be simplified using an object instead of a 2D array, and with Array#map:

function pairElement(str) {
  var pairs = { 'G': 'C', 'C': 'G', 'A': 'T', 'T': 'A' };
  return str.split('').map(ch => [ch, pairs[ch]]);
}

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

Upvotes: 1

Related Questions