r/javaScriptStudyGroup • u/[deleted] • Feb 08 '16
Question about creating 2d arrays
function pair(str) {
var string = str.split("");
var newArr = [];
for (var i = 0; i < string.length; i++) {
var temp = [];
if (str[i] === "G") {
temp.push(str[i] + "C");
} else if (str[i] === "C") {
temp.push(str[i] + "G");
} else if (str[i] === "A") {
temp.push(str[i] + "T");
} else if (str[i] === "T") {
temp.push(str[i] + "A");
}
newArr.push(temp);
}
return newArr;
}
pair("GCG");Im getting [ [ 'GC' ], [ 'CG' ], [ 'GC' ] ] If I didn't create the empty temp array where I pushed in the letters BEFORE pushing the temp array into the newArr outside of the loop, I would get only one array -- [ 'GC' , 'CG', 'GC' ]. Can someone please explain why I am getting a 2d array now? Like I thought it just pushing every letter (plus the second letter) into the temp array and THEN pushes it all to the newArr- but that can't be it because then I would again not get a 2d array-meaning that for example: it pushes first the G+C into temp, then RIGHT AWAY into newer, then again pushes A+T into temp and then right away into newer etc and I don't understand why it pushes it right away into newArr without finishing first the loop? Thanks
1
u/ForScale Feb 11 '16
Hey there! Looks like /u/Volv gave you a good answer.
Thanks for posting in the group here! Feel free to message any of us directly if you don't get a response right away. And feel free to participate in the weekly focuses!