Question about flattening an array

0

I understand the concept of what is happening, but I’m trying to grasp the how it is happening. Once I get to this line, flat = flat.concat(flatten(arr[i])), I am a little unclear as to how that specific subarray that is about to be looped through makes it to flat = [ ]. I understand once the function is called again, the sub array is basically being worked on as if it was not a sub array, and starts going though the loop. The arr[i] makes it down to flat.push(arr[i]); Is it at that point that the arr[i] items are being pushed into flat = [ ], or are they being pushed/ directed here flat.concat(flatten(arr[i])) to be resolved and concat’ed when the sub array has finished going through the loop? What is confusing to me is, if they are just be pushed straight into the flat = [ ] using flat.push(arr[i]), what is there to .concat? No info/ data would be there to be able to concat on this line flat.concat(flatten(arr[i])) Any clarity would be greatly appreciated!!

 const arr = [[1, 2, 3], [4, [5, 6]], [[7], [8, [9]]], 10]

 function flatten(arr) {
     let flat = [] ;
     for (let i = 0; i < arr.length; i++) {
       if (Array.isArray(arr[i])) {
         flat = flat.concat(flatten(arr[i]));
       } else {
         flat.push(arr[i]);
       }
     }
     return flat ;
   }
1 Like

Hello, I have edited your subject line to include a more helpful description of this topic. Hopefully this will help you get some good answers as well.

This is from Steamroller guide page?

Here is some recursion going on, that means two things:

  1. explanation would be verbose(I don’t have skills to provide laconic explanation about recursion)
  2. running this code here may be helpful to understand what’s going on exactly

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