0

this code is only iterating the first 9 nos in the nested array.

var arr = [[[1,2,3,4,5,6,7,8,9],[1,2,3,4]]];
 for (var i=0; i < arr.length; i++) {
 for(var j = 0; j < arr[i].length; j++) {
 for(var k = 0; k < arr[j].length; k++){
 console.log(arr[i][j][k]); 
 }; 
 }; 
};
Ala Eddine Menai
2,9047 gold badges32 silver badges61 bronze badges
asked Jun 24, 2020 at 18:36
3
  • 3
    The third loop should use arr[i][j].length Commented Jun 24, 2020 at 18:41
  • Is it necessary to use for-loop for you ? Commented Jun 24, 2020 at 18:44
  • Hi Menai - did you mean there is a better method? pl suggest. Commented Jun 24, 2020 at 19:15

3 Answers 3

2

The Problem is with the third loop. Corrected Code -

for (var i=0; i < arr.length; i++) {
 for(var j = 0; j < arr[i].length; j++) {
 for(var k = 0; k < arr[i][j].length; k++){
 console.log(arr[i][j][k]); 
 }; 
 }; 
 };
answered Jun 24, 2020 at 18:43
Sign up to request clarification or add additional context in comments.

Comments

0

You had missed an iterator on your second loop Here

for(var i=0;i<arr.length;i++){
for( var j=0;j<arr[i].length;j++){
 for (var k=0;k<arr[i][j].length;k++)
 console.log(arr[i][j][k]);
}

}

answered Jun 24, 2020 at 18:46

Comments

0

You can also use Foreach as an alternative way to loop your array.

 const iterate = (arr) =>
 arr.forEach((arrOne) =>
 arrOne.forEach((arrTwo) => arrTwo.forEach((value) => console.log(value)))
 );
answered Jun 24, 2020 at 18:58

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.