Problem call stack being exceeded when using recursion on array flattening challenge

I tried the recursive function here (first post marked as answer): https://stackoverflow.com/questions/45218858/deep-flat-multidimensional-array-in-javascripthttps://stackoverflow.com/questions/45218858/deep-flat-multidimensional-array-in-javascript to try to solve this, but it gives me an error in the console that says:

RangeError: Maximum call stack size exceeded

I’d really like some help here. Thanks.

My code so far


function steamrollArray(arr) {
const deepFlatten = (array) => {
  let result = [];
  for (const elem of array) {
    if (Array.isArray(elem)) {
      result = array.concat(deepFlatten(array));
    } else {
      result.push(elem);
    }
  }
  return result;
}
return deepFlatten(arr);
}

console.log(steamrollArray([1, [2], [3, [[4]]]]));

Your browser information:

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

Challenge: Steamroller

Link to the challenge:

Seems it only works when I use forEach. But I’ve heard that it’s not advised to use this function. So what alternatives, if any, do I have?

Where did you hear this? What was the explanation?