umairhp
1
Tell us what’s happening:
What else do i need to do here?
Your code so far
function pairElement(str) {
var arr = str.split("");
console.log(arr);
var newArr = [];
for (i = 0; i < arr.length; i++) {
arr.forEach(function(item) {
newArr.push([item[i], item[i+1]]);
})
return newArr;
}
}
pairElement("GCG");
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/dna-pairing
umairhp
2
Yes! I was able to do it:
function pairElement(str) {
var arr = str.split("");
console.log(arr);
var newArr = [];
for (i = 0; i < arr.length; i++) {
if (arr[i] == 'G') {
newArr.push([arr[i], 'C']);
}
else if (arr[i] == 'C') {
newArr.push([arr[i], 'G']);
}
else if (arr[i] == 'A') {
newArr.push([arr[i], 'T']);
}
else {
newArr.push([arr[i], 'A']);
}
}
return newArr;
}
pairElement("ATCGA");
lasjorg
3
Good job.
(i = 0 …)
This will create a global variable, declare the variable in the initialization (var i = 0), or before the loop inside the function.
Looking at the OP, i just want to point out that you can get the index inside a forEach by passing the index to the callback function
someArray.forEach( function(element, index) {
});
umairhp
4
You mean I wouldn’t need a for loop if I pass the index as an argument?
lasjorg
5
Yes, you get access to the index of the array inside the forEach.
But you don’t even need the index:
function pairElement(str) {
var arr = str.split("");
var newArr = [];
arr.forEach((ele) => {
if (ele == 'G') {
newArr.push([ele, 'C']);
} else if (ele == 'C') {
newArr.push([ele, 'G']);
} else if (ele == 'A') {
newArr.push([ele, 'T']);
} else {
newArr.push([ele, 'A']);
}
});
return newArr;
}