I grasp the concept, but I am struggling to understand the process.
Once it reaches this line:
flat = flat.concat(flatten(arr[i]))
I fail to comprehend how that specific subarray which is about to be iterated through ends up in
flat = []
.
I realize that when the function is called again, the subarray is essentially being treated as if it were not a subarray and begins to loop through its elements.
The arr[i]
eventually reaches flat.push(arr[i]);
At that point, are the items within the arr[i]
pushed into flat = []
, or are they directed to flat.concat(flatten(arr[i]))
to be resolved and concatenated once the entire subarray has been traversed?
My confusion lies in whether the items are directly pushed into flat = []
using flat.push(arr[i])
or if there is data present to be able to .concat
at the line flat.concat(flatten(arr[i]))
What am I overlooking?
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;
}