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]);                      
        };                          
    };    
};
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]);                      
        };                               
       };  
    };
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]);
}

}

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)))
  );

Comments

Your Answer

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.