Examples
Write flatten so that the following cases hold.
- Input
flatten([1,[2,[3,[4]]]])Output[1,2,3,4] - Input
flatten([[],[1],[]])Output[1] - Input
flatten([1,2,3])Output[1,2,3]
1 more hidden test cases - 4 in total will be graded.
Answer
js
function flatten(arr) {
return arr.reduce(
(acc, item) => acc.concat(Array.isArray(item) ? flatten(item) : item),
[],
);
}
flatten([1, [2, [3, [4]]]]); // [1, 2, 3, 4]
arr.flat(Infinity) exists, but interviews usually want the recursion. Nested empty arrays ([[], [1], []]) must yield [1].
