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!
3
u/Volv Feb 08 '16 edited Feb 08 '16
You are pushing strings into a temp array and then pushing a temp array onto the result array.
Commented to show the workings.
The push to newArr is done at the end of each loop iteration and the final result returned at end of function. The indentation was possibly not helping understanding in your pasted code.
Looks like you want to build the string inside the loop and push the string to the result array.