Steamroller - oversimplification?

This is the first time I am trying recursion. And I am PRETTY sure that I’m oversimplifying my code. But can someone else take a look and tell me what I am missing?

My code so far:


function steamrollArray(arr) {

    let flatArray = [];


    if(!Array.isArray(arr)){
      flatArray.push(arr);
    }else{
      steamrollArray(arr);
    }
return flatArray;
}

Also, the error I am getting in console.log is:

Uncaught RangeError: Maximum call stack size exceeded
    at Function.isArray (<anonymous>)
    at steamrollArray (FCC.js:6)
    at steamrollArray (FCC.js:9)

ad infinitum :cry:

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/steamroller

arr always is array, so you return always arr.

I think your logic is almost correct except that,as @yoelvis mentioned, you are evaluating the original array passed as an argument. You have to evaluate the element of the array. I changed your code slightly and it works.

var flatArray = [];

function addArray(arr){
arr.forEach(val=>{
if(!Array.isArray(val)){
flatArray.push(val)
} else {
addArray(val)
}
})
}

function steamrollArray(arr) {
flatArray=[];
addArray(arr);
return flatArray;
}

Thank you @danielchae. Your code made complete sense.

I do have a couple of questions:

  1. Why do you have to declare variable (and initialize it to empty array) but then have to re-initialize it again inside steamrollArray function? Is that just to avoid the result from previous execution of code from crossing into future execution of code?

  2. Would it be possible to have the addArray function defined inside the steamRollArray function? I guess it’s not important. But I tried to do just that and all my test cases failed:

function steamrollArray(arr) {
  var flatArray = [];
  function addArray(arr){
    arr.forEach(val=>{
      if(!Array.isArray(val)){
        flatArray.push(val)
      } else {
        addArray(val)
      }
    })
  }
  return flatArray;
}

Thank you.

Hi @sabbyiqbal,

I just wanted to make things clear so I divided them into different pieces. Your code will work as well and actually that is better coding.

What you missed here is calling addArray function inside streamrollArray function. it was only defined but not called. if you add “addArray(arr)” right before return statement it will work.

1 Like

Thanks so much @danielchae and @yoelvis. Recursion is tough to wrap my head around but I got a little closer to understanding :sunglasses: