0
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']]

1 Answer 1

1

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"));

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

4 Comments

Cool is there anyway i can do it functionally ?
@SeanT Certainly, the second code snippet is more functional.
Ohh yeah I've seen that code snippet too , but i don't know ECMA6 so wanted something functional in ECMA5 :)
For ES5, change ch => [ch, pairs[ch]] to function(ch) { return [ch, pairs[ch]]; }

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.