Why my for increase the index by 2 instead of 1?

Hi, im trying to solve the " Steamroller" Task of the “Intermediate algorithm scripting”
I know that my code could looks little tricky but Im trying to solving this with my personal and rudimental approach to improve my loop skills maybe i could try recursion in the future.
Im trying to use two for loops to iterate into the nested arrays and look if every elements is or not an array, if not then push into a new array, the thing is that my index of the second for increase two units instead of one.

I left some console.log()'s to debug and catch this weird behaviour


function steamrollArray(arr) {
    var newArr = [];
    for(let i = 0; i <= arr.length - 1; i++){
        if(!Array.isArray(arr[i])){
            console.log(arr[i])
            newArr.push(arr[i])
            console.log('first level');
        }
        else{
            for(let j = 0; j < arr[i].length+1; j++){
                if(!Array.isArray(arr[j])){
                    console.log(arr[i][j]);
                    console.log(i,j);
                    
                    //console.log(arr[i][j]);
                    newArr.push(arr[i][j]);
                    console.log('second level');
                }
            }
        }
        
        //console.log(arr[1][1]);
        
        
    }
    console.log(newArr);
    //return newArr;
  }
  
// console.log(  steamrollArray([1, [2, 3]]));


steamrollArray([1, [2, 3]])




  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36.

Challenge: Steamroller

Link to the challenge:

What’s going on here?

im trying to iterate until j reach the length of the first nested array,already tryed j <= arr[i].length - 1 like the first for loop but then turn this condition into what it is now, same effect

I’m understand the logics around the index of the arrays about: first element is the index 0 and then… but i dont know what’s happening here. actually I’m pretty sure its about that for condition you mention but still not find the point.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.