Question about recursive function ex from MDN

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?

You can flatten to a specific depth. By default it only flattens one level if you don’t pass the second argument. So it flattens once, then d - 1, d is now 0, return the result.

If you wanted to flatten two levels, pass 2 to the function: flattens once, d - 1, flattens again, d - 1, d is now 0, return the result.

If you pass Infinity, infinity - 1 is infinity, so it just keeps going until it can’t find any sub-arrays to flatten, at which point it also returns the result.

1 Like