JavaScript utilities · Core · about 15 minutes
Flatten
Implement flatten(list, depth = 1) without Array.prototype.flat or flatMap (the tests remove them). Return a new array in which nested arrays are flattened up to depth levels. depth may be Infinity (shown as null in the test input). Do not change the input.
Start from
function flatten(list, depth = 1) {
// Return a new array, flattened up to depth levels.
}Hints
Each hint gives away a little more. Open one only when you need it.
Hint 1
Walk the items. An array with depth left is flattened with depth - 1; anything else is pushed as it is.
Hint 2
Recursion is the shortest form. An interviewer may then ask for a version with a stack, for very deep input.
Solution
From here on the page gives the method away. If you are still solving, go back to the hints.
JavaScript
function flatten(list, depth = 1) {
const out = [];
for (const item of list) {
if (Array.isArray(item) && depth > 0) out.push(...flatten(item, depth - 1));
else out.push(item);
}
return out;
}What an interviewer looks for
A recursion check. The follow-ups are the iterative version and what happens with a very deep array.