Tell us what’s happening:
Hello everyone. First post. I’m a little confused as to why the spread operator is needed, or works the way it does in solution 1:
My code (similar to solution 1):
function steamrollArray(arr) {
let dataFromArr = [];
for (let x = 0; x < arr.length; x++) {
if (Array.isArray(arr[x])) {
dataFromArr.push(...steamrollArray(arr[x])); // <-- here
} else {
dataFromArr.push(arr[x]);
}
}
return dataFromArr;
}
steamrollArray([1, [2], [3, [[4]]]]);
As far as I understand the spread operator, it will copy all elements in the object or array referenced. Okay. However, since I am recursively drilling down to the element, why does simply pushing the element into a different array take all it’s nesting with it? Shouldn’t it just be that element?
current output:
[ 1, 2, 3, 4 ]
without spread operator:
[ 1, [ 2 ], [ 3, [ [Object] ] ] ]
I guess that’s just how it is?
Thanks for any help.
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:105.0) Gecko/20100101 Firefox/105.0
Challenge: Intermediate Algorithm Scripting - Steamroller
Link to the challenge: