Why the code produces [1, 2], [3, 4], [1, 2], [3, 4], [1, 2], [3, 4]. What happened to the element array [5, 6] ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why the code produces [1, 2], [3, 4], [1, 2], [3, 4], [1, 2], [3, 4]. What happened to the element array [5, 6] ?

var arr = [[1, 2], [3, 4], [5, 6]]; for(var i=0; i < arr.length; i++) { for(var j=0; j < arr[i].length; j++) { console.log(arr[j]); } } Though I do understand when the console log is either: console.log(arr[i]) or console.log(arr[i][j])

31st Jan 2017, 8:17 PM
Benneth Yankey
Benneth Yankey - avatar
8 Answers
+ 8
for(var i=0; i < arr.length; i++) { for(var j=0; j < arr[i].length; j++) { console.log(arr[i][j]); } }
31st Jan 2017, 8:21 PM
Valen.H. ~
Valen.H. ~ - avatar
+ 7
Last value of "j" is 1 (it should be 2, your code is wrong, practise on the code I sent…)
31st Jan 2017, 9:06 PM
Valen.H. ~
Valen.H. ~ - avatar
+ 7
Yes! I said that's wrong!… ~_~
31st Jan 2017, 9:15 PM
Valen.H. ~
Valen.H. ~ - avatar
+ 4
To develop @VH answer: You attempt to access a bidimentional array with an unique index ( even if you iterate through two index variables ), so you log the 'rows' elements with the index of your 'cols' elements ( 'j' iterate over length of 'arr[i]', but next you access arr[j] instead arr[i][j] )...
31st Jan 2017, 8:43 PM
visph
visph - avatar
+ 3
With arr[i][j] output is: 1 - 2 - 3 - 4 - 5 - 6... one sub-item by one. With arr[i] output is 1, 2 - 1, 2 - 3, 4 - 3, 4 - 5, 6 - 5, 6... one sub array repeat twice, one per line/output With arr[j] output is 1, 2 - 3, 4 - 1, 2 - 3, 4 - 1, 2 - 3, 4: because you iterate over the sub arrays, in index range of sub array length ( always two while length of arr is three ), all this 3 times repeated since you too iterate over index range of arr with the 'for' loop over 'i' ^^
31st Jan 2017, 9:16 PM
visph
visph - avatar
+ 1
@ValentineHacker thanks didn't get u at first, u mean it's ethically bad code after all it's bidirectional iteration yet accessing only one index. Thanks really grateful
31st Jan 2017, 9:20 PM
Benneth Yankey
Benneth Yankey - avatar
0
I guess you didn't get my question: I have no problem if the console log is: console.log(arr[i]) or console.log(arr[i][j]) The problem is console.log(arr[j]), I don't seem to understand why [5, 6] does not print in the result. I need practical explanation please.
31st Jan 2017, 9:04 PM
Benneth Yankey
Benneth Yankey - avatar
0
@ValentineHacker I do understand your code very much well the console.log prints 1, 2, 3, 4, 5, 6 replace the console log in your code to console.log(arr[j]) to get what I mean. Thanks
31st Jan 2017, 9:13 PM
Benneth Yankey
Benneth Yankey - avatar