I am struggling to understand the following code:
let myArray = ["J", "a", "v", ["a", "scrip"], "t"];
const flatten = (myArray) => {
return myArray.reduce((flat, arry) => {
return Array.isArray(arry) ? flat.concat(flatten(arry)) : flat.concat(arry);
}, []).join("");
};
console.log(flatten(myArray));
// Output => Javascript
I’m confused about why the flatten
"Main function" is called inside the reduce
function with the arry
parameter. Since the reduce
function goes through the myArray
, why is it necessary? When I tried removing the flatten
call inside the reduce
callback function, as in the following:
const flatten = (myArray) => {
return myArray.reduce((flat, arry) => {
return Array.isArray(arry) ? flat.concat(arry) : flat.concat(arry);
}, []).join("");
};
console.log(flatten(myArray))
the code produced the same outcome. So, why is the main function call needed, and how does it make a difference? I just need to understand how things really work.
Thanks for your help.
2
Answers
The difference is recursion.
If you do the first version, it doesn’t matter how deep the array goes, it always returns
Javascript
, but if you take out the recursion, then you end up with something else.With recursion
Without recursion
You can run the code snippets to see, how they return different results.
That is called recursion. The idea is that you iterate through the array, if another array is found, then call the same function again the that array. Otherwise, just concat the value to the result.
Use the following array and run the code with and without calling
flatten
recursively, you’ll see the difference.let myArray = ["J", "a", "v", ["a", "scrip"], "t", [' ','is', [' ', 'awe', ['some']]]];