When flattening an Array, when is arr[ i ] being added to the new array (flat)? Is it by flat.push() or by flat.concat()?

Viewed 44

I understand the concept, but I don't understand how it is happening.

Once I get to this line:
flat = flat.concat(flatten(arr[i]))
I do not understand how that specific sub array that is about to be looped through makes it to flat = [].

I understand once the function is called again, that the sub array is basically being worked on as if it were 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 confuses me is that if they are just pushed straight into flat = [] using flat.push(arr[i]), what is there to .concat?

There would be no info/data there to be able to concat on this line flat.concat(flatten(arr[i]))

What am I missing?

    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 Answers

It's a pretty straightforward recursive function

it takes an array or an element and return a new array with the concat of the flatten array or the element

it does the same of Arr.flat(Infinity)

you can check with the code above

 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 ;
   }

console.log(flatten(arr))
console.log(arr.flat(Infinity))

Related