Flatten Array
Objective: Write a function that takes a nested array and returns a flat array with all elements at the same level.
Instructions:
- Create a function called
flattenArray
that accepts an array containing nested arrays of various depths.
- The function should return a new array where all the elements are "flattened" to the top level (i.e., no nested arrays).
Example:
flattenArray([1, [2, 3], [4, [5, 6]]]);
// Output: [1, 2, 3, 4, 5, 6]
Requirements:
- The function must handle arrays with multiple levels of nesting.
- You cannot use the built-in
Array.prototype.flat()
method.
- The function should work recursively to ensure that deeply nested arrays are also flattened.
Hints:
- Use
recursion
to handle arrays nested at multiple levels.
Concatenation
or spreading
can help combine arrays when flattenin
Bonus:
- Add a second argument to the function that limits how deep it should flatten the array (like
Array.prototype.flat(depth)
).