What is the purpose of d-1 on the recursive call.
Example of how to flatten a nested array using recursion.
const arr = [1, 2, [3, 4, [5, 6]]];
// to enable deep level flatten use recursion with reduce and concat
function flatDeep(arr, d = 1) {
return d > 0 ? arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatDeep(val, d - 1) : val), [])
: arr.slice();
};
flatDeep(arr, Infinity);
// [1, 2, 3, 4, 5, 6]
I get we call the function using Infinity .
Then on the actual function we set d and default it to 1 if not argument is passed in.
However, it states if the value we currently are in is of type array call the function again but decrease d by 1.
What is the purpose of this?