I have found this interesting code example which flattens an array using the recursion
and reduce
function instead of flat
. I get what it does except the following:
acc = acc.concat(flatWithRec(item));
why accumulator is being reassign? how is it possible in reduce function? and why useconcat
here?return acc;
why acc is being returned? is it a new Flat Array each time function is called?is there a way to, still, use recursion and make it easier for the reader to understand?
Please clarify
function flatWithRec(arr) {
const flatArray = arr.reduce((acc, item) => {
if (Array.isArray(item)) {
acc = acc.concat(flatWithRec(item));
} else {
acc.push(item);
}
return acc;
}, []);
return flatArray;
}
console.log(flatWithRec([1, [2, 3, [4],
[5, 6, [7]]
]]))
// output: [1, 2, 3, 4, 5, 6, 7])