Intermediate Algorithm Scripting Question: Steam Roller

Hello,

I spent a few hours trying to figure this one to no avail. After checking the first answer, the recursive solution makes a lot of senses to me but I am have a hard time getting around what is happening with the rest operator:

function steamrollArray(arr) {
  const flattenedArray = [];
  // Loop over array contents
  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      // Recursively flatten entries that are arrays
      //  and push into the flattenedArray
      flattenedArray.push(...steamrollArray(arr[i]));
    } else {
      // Copy contents that are not arrays
      flattenedArray.push(arr[i]);
    }
  }
  return flattenedArray;
};

// test here
steamrollArray([1, [2], [3, [[4]]]]);

I added some tests:

function steamrollArray(arr) {
  const flattenedArray = [];
  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      console.log(arr[i]);
      flattenedArray.push(...steamrollArray(arr[i]));
    } else {
      console.log('Add ' + arr[i]);
      flattenedArray.push(arr[i]);
    }
  }
  console.log('Result ' + flattenedArray);
  return flattenedArray;
}

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

I get the same result with or without the spread operator.
It won’t pass the freecodecamp test however.

Can someone explain to me what’s going on here?

Is there something you don’t understand about the solution?
Without the spread operator, flattenedArray just gets an array pushed onto it, not individual values.

1 Like

I have added spoiler tags to this code since you posted a solution.


Your console.log() is misleading. I would instead use

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

I actually I just found out that console.log output was misleading because of how I setup my test. Ie:

A friend told me its got something to do with implicit type conversion.

function steamrollArray(arr) {
  const flattenedArray = [];
  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      console.log(arr[i]);
      flattenedArray.push(steamrollArray(arr[i]));
    } else {
      console.log('Add ' + arr[i]);
      flattenedArray.push(arr[i]);
    }
  }
  console.log('Result ' + flattenedArray);
  return flattenedArray;
}

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

module.exports = steamrollArray;

This is what was causing the problem . The output was misleading. Now that the output is giving me what I am expecting there is no confusion. :wink:

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