Intermediate Algorithm Scripting - Steamroller

Tell us what’s happening:
So I can get as far as flattening most of the array down, however I don’t understand why my reduce function stops before completely flattening the array. because as it goes across the array, before it finds the integer 4. Array.isArray should return true and therefore continue to concat the array no?

Your code so far

function steamrollArray(arr) {

  console.log(arr.reduce((acc, item) => { 
   if (Array.isArray(item)){
     return acc.concat(item);
   } else {
     return [item];
   }
},[])

)
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36

Challenge: Intermediate Algorithm Scripting - Steamroller

Link to the challenge:

This line I’m concerned about.

The return value from the reduce callback generally needs to involve acc

So I updated it sprading my acc as such:

return [...acc, item];

still no dice my console log just shows:

[ 1, 2, 3, [ [ 4 ] ] ]

Better but now you found the other problem.

You need a way to handle multiply nested arrays. You removed one layer of depth around that 4 instead of every layer of depth.

There are a few ways to do this.

I hated this one with a passion. With the fire of a thousand suns.

1 Like

Getting the arbitrary depth of nesting is tricky for sure. Lots of ways to attack it

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