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 useconcathere?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])
reduceif that makes it easier to understand (or at least help figuring out what thereducedoes)acc.concat(..)returns a new array and doesn't mutate the original arrayacc. So, they are reassigning. You could do it without reassigning usingpushlike thisacc.push(...flatWithRec(item))reducecallback. It's how reduce works.