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?