Pak Hang Leung
Pak Hang Leung

Reputation: 389

Concept about flatten use recursion with reduce and concat

Now I would like to flattening the array with multiple layers

From the other solution before and the developer's network, There is an effective solution:

var arr1 = [1,2,3,[1,2,3,4, [2,3,4]]];

function flattenDeep(arr1) {
   return arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
}
flattenDeep(arr1);// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]

However, there is a couple questions about the theory at that back that I want to ask: 1. In my understanding, the function starts with initial value acc, and then it keeps looping all the element to see if it is an array or not.

In this case, the first 3 elements are 1,2,3 -- therefore is not an array and will be accumulated and returned as an array.

But start from the fourth element it returns

Array.isArray(arr1[3]) 
(5) [1, 2, 3, 4, Array(3)]

In this case, it triggers the condition acc.concat(flattenDeep(val)), which is a recursion of the function. How this condition helps to flatten the array?

And for the [] at the back, if my understand is right, it indicates the return form of the result from reduce should be an array?

Last but not least, any good reference for this topics that I should look for?

May thanks for your help!

Further elaboration:

let's say, now the val in the reduce function above is [1, 2, 3, 4,[[2,3,4]]].

In this first round of checking, the elements 1,2,3,4 are not array, but the last element still does, and it makes the whole argument still an array. For the next round of the recursion, would it just take the element [[2,3,4]]] and further evaluate the elements inside this array?

Or with this example, what would be the first, second and third round outcome of the recursion process?

Upvotes: 2

Views: 322

Answers (1)

Papi
Papi

Reputation: 769

Second argument in the reduce method is the starting condition. If there is nothing provided, first acc will be the first array's element (see array.prototype.reduce on mdn).

I'm not sure about the But there is nth to indicate the reduction of the array statement. You're calling function recursively until you will find something that's not an array and then you're returning that value.

Look for js call stack, understand how js is stacking the functions, you can even draw it, it will help definitely because it's not easy case :)

Upvotes: 2

Related Questions