Steamroller exercise

Steamroller exercise
0

#1

Dear fellows,

Could somebody assist me with steamroller exercise I would like to know why the below code is not functioning properly especially with the recursive method.

here is my code

function steamrollArray(arr) {
 return flat(arr);
}

var flat=function(arr2)
{
  var result=[];
 while(arr2.length!==0)
   {
     if(Array.isArray(arr2[0])===false)
       {
         result.push(arr2[0]);
         arr2.shift();
       }
     else
     {
       flat(arr2[0]);
       arr2.shift();
       
     }
     
   }
  
  return result;
};

steamrollArray([1, [2]]);

#2

I added some console.logs to your code, so you can see what is happening. See if this points you in the right direction.

function steamrollArray(arr) {
  return flat(arr);
}

  var flat=function(arr2) {
  var result=[];  
  console.log('entering flat function')

  console.log('next line shows result contents before  while loop')
  console.log(result)
  while(arr2.length!==0) {
    console.log(arr2[0])
    if(Array.isArray(arr2[0])===false) {
      console.log('not array')
      result.push(arr2[0]);
      arr2.shift();

    }
    else {
      console.log('is array')
      flat(arr2[0]);
      arr2.shift();
    }
    console.log('arr2.length = '+arr2.length);
    console.log('next line shows result contents after if statement')
    console.log(result)
    console.log()
  }
  return result;
};

steamrollArray([1, [2]]);

#3

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.