Open boxes inside boxes
You tip out a drawer and find a box of things, and inside that box another box. To get one flat pile you do not stop at the first box: you open each one you meet, and if what you pull out is itself a box, you open that too. Boxes inside boxes, however deep the stack goes.
A nested array is the same picture. [1, [2, [3, 4]], 5] holds numbers and more
arrays, and those arrays can nest as deep as they like. The self-similar step is
to walk the list and hand any element that is itself an array to the same rule.
The task on a nested array is the task on its inner arrays.
You need a case that opens nothing: a plain value, like a number. It is already flat, so you keep it as it is. That is the base case — only recurse when there is something left to open.
Shrink the input by passing each inner array to a smaller run of the function, so
every level gets flattened in turn. Then trust the call: assume
flattenDeep(element) already returns that element fully flattened, and collect
what it gives back.
function flattenDeep(list) {
return list.reduce((flat, element) => {
if (Array.isArray(element)) {
return flat.concat(flattenDeep(element));
}
return flat.concat(element);
}, []);
}
Each call opens one level and trusts the calls below it to open the rest.
Export flattenDeep from index.js. It returns a new array with every level of
nesting removed, keeping the values in order.
Challenge
A box can hold another box, which holds another, deeper than you can see in
advance. Export a flattenDeep function from index.js that opens every level
into one flat list.
flattenDeep takes an array whose items may be nested arrays of any depth and
returns a new array holding the values in order, with no arrays left inside. A
value that is not an array is kept as it is.