This function is to flatten an array with nested arrays inside:
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]]]]);
Why do we use the spread (…) in line 5? What does it actually do to the input? I wrote the whole thing without it but couldn’t understand how I would know to use it!
Thanks