Flatten Array
EasyArrays15 min6 tests
Implement flatten(value) — collapse a deeply nested array into a single flat array, left to right.
Implement flatten(value) which takes a deeply nested array and returns a new, fully flattened array — every nested level collapsed into a single flat array, left to right.
Requirements
- Flatten arrays of arbitrary depth.
- Preserve the original left-to-right order.
- Don't mutate the input.
- An already-flat array (or an empty array) comes back unchanged.
Example
flatten([1, [2, [3, [4]], 5]]); // → [1, 2, 3, 4, 5]Hints (4)
- Walk the input element by element and decide, for each one, whether it is itself an array.
- Use
Array.isArray(item)to detect a nested array. - When an element is an array, recurse into it and spread the flattened result into your output.
- Build a brand-new array (push into it) so you never mutate the input.
Topics
- Arrays
- Recursion
Asked at
Amazon · Apple · Microsoft
