My solution uses a nested for loop that compares the value of the first index of each subarray in the variable basePairs with the value of each index in the argument str. If true, then it pushes the value to a new array dnaPairs.
function pairElement(str) {
var basePairs = [["G","C"],["C","G"],["A","T"],["T","A"]];
var dnaPairs = [];
for (var i = 0; i < str.length; i++){
for(var j = 0; j < basePairs.length; j++){
if (str[i] === basePairs[j][0]){
dnaPairs.push(basePairs[j]);
}
}
}
return dnaPairs;
}
pairElement("GCG");
I used an object to set up the pairs, converted the str into an array and then used map to iterate over it. On each iteration I checked if the current argument is a property of the object and push the key value pair into a new Array.
function pairElement(str) {
var basePair = {
"A":"T",
"T":"A",
"C":"G",
"G":"C"
};
var result = [];
var strToArr = str.split("").map(function(elem) {
if(basePair.hasOwnProperty(elem)) {
result.push(new Array(elem, basePair[elem]));
}
});
return result;
}
pairElement("GCG");
This is my solution. First time using a switch statement in a while.
function pairElement(str) {
//splits string into array of characters
str = str.split("");
//iterates through characters to match them up
for (var i = 0; i < str.length; i++) {
switch (str[i]) {
case "G":
str[i] = str[i] + "C";
break;
case "C":
str[i] = str[i] + "G";
break;
case "A":
str[i] = str[i] + "T";
break;
case "T":
str[i] = str[i] + "A";
}
//separates strands into array of arrays
str[i] = str[i].split("");
}
return str;
}
pairElement("CTCTA");
I made the base pairs into a string (βATCGβ) and then devised a formula to find the index of partners in a string of consecutive pairs. A little overkill, what with only two pairs, but I just love any opportunity to use the modulo operator!
function pairElement(str) {
var basePairs = "ATCG";
var strand = [];
for (var i = 0; i < str.length; i++) {
var pair = [];
pair.push(str[i]);
var bpIndex = basePairs.indexOf(str[i]);
var partnerIndex = bpIndex + 1 + (-2 * (bpIndex % 2));
pair.push(basePairs[partnerIndex]);
strand.push(pair);
}
return strand;
}
let pairElement = (str) => {
let DNA = { "A": ["A", "T"], "T": ["T", "A"], "C": ["C", "G"], "G": ["G", "C"] };
let strArr = str.split("");
let DNA_Pairs = [];
for (i = 0; i < strArr.length; i++) {
let value = strArr[i];
DNA_Pairs.push(DNA[value]);
}
return DNA_Pairs;
};