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.
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
let myArray = ["J", ["a", "v"], ["a", "s", ["c", ["r", "i"], "p"]], "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))
Without recursion
let myArray = ["J", ["a", "v"], ["a", "s", ["c", ["r", "i"], "p"]], "t"];
const flatten = (myArray) => {
return myArray.reduce((flat, arry) => {
return Array.isArray(arry) ? flat.concat(arry) : flat.concat(arry);
}, []).join("");
};
console.log(flatten(myArray))
You can run the code snippets to see, how they return different results.