Steamroller (Need Help)

function steamrollArray(arr) {

//Check to see if an element is an array or not
Array.isArray(arr);
// If element is an array...then flatten it aka [2] => 2 

  return arr;
}

console.log(steamrollArray([1, [2], [3, [[4]]]]));

I am confused about how I can flatten an array without the flat() method. Can someone please help me out?

You need to create a process that recreates the effect of the flat() method.

function steamrollArray(arr) {

let ans = []; 

for (let i = 0; i < arr.length; i++) {
  if (Array.isArray(arr[i])) {
    ans.push(steamrollArray(arr[i]))
  } else {
    ans.push(arr[i])
  }  
}
return ans;
}

console.log(steamrollArray([1, [2], [3, [[4]]]]));

Thanks! I was overcomplicating it. I still can’t figure out what I am doing wrong though

What is being pushed here?

The elements that are arrays right? Then in my else statement I am pushing the rest of the elements that are not arrays

This function call returns a ____

Ohhh steamrollArray(arr[i]) would only push the array at index 0, instead of checking for everything in the steamrollArray?

Huh? I don’t think so

Can you answer this question?

a flattened array, but I know I am doing it wrong

It returns an array as you say. What happens if you push an array onto another array?

console.log([1, 2].push([3]));

What does this do?

Honestly, I would have thought that would return [1, 2, [3]] but I am noticing it only returns 3. I thought the push() method pushed whatever you put inside of it to the back of the array. Now I feel dumb :upside_down_face:

Right idea, bad example syntax on my part.

The core issue is that push doesn’t join arrays. How can you join two arrays?

The concat() method or you could use the varargs method aka ... so the method is allowed to accept an indefinite amount of arguments of the same type?

Try it. Those both sound promising

1 Like

It worked, thank you so much for your help!! :slight_smile:

1 Like

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