Hello, Need some help to underestand code!

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]]]]);

Hello guys, I would like to know why in this code is used the spread operator and what it actually does, I can’t actually get it. Thanks!

push takes multiple arguments.

const someNumbers = [42, 1];

someNumbers.push(3);
console.log(someNumbers); // [42, 1, 3]

someNumbers.push(5, 6, 7);
console.log(someNumbers); // [42, 1, 3, 5, 6, 7]

You can use the spread operator to spread out an array as multiple arguments to a function

const someNumbers = [42, 1];
const someMoreNumbers = [5, 6, 7];

someNumbers.push(...someMoreNumbers);
console.log(someNumbers); // [42, 1, 5, 6, 7];
1 Like

Woah, you got recursion going on already… I still have to go back to that topic Nth times to completely understand it. Good job Mike, hope you’ll get this working.

1 Like

Thanks, I think I lost it , but now I can better get what it actually does! Because the array we’re passing has different levels!