// Very frequently asked question
// Write custom function for Array.flat() using both recursive and iterative
// const flattenRecursive = (arr) => {
// const flattenIterative = (arr) => {
// // Write a function to flatten a nested array up to a given depth
// const flattenRecursiveWithDepth = (arr) => {
// Recursive Approach without Depth
const flattenRecursive = (arr) => {
if (!Array.isArray(arr)) {
throw new Error("Input must be an array");
if (Array.isArray(ele)) {
result.push(...flattenRecursive(ele));
const resultRecursive = flattenRecursive(
[[[[0]], [1]], [[[2], [3]]], [[4], [5]]]
console.log(resultRecursive, "Recursive Result");
// Iterative Approach without Depth
const flattenIterative = (arr) => {
if (!Array.isArray(arr)) {
throw new Error("Input must be an array");
if (Array.isArray(ele)) {
// Test case for Iterative Approach
const resultIterative = flattenIterative([[[[0]], [1]], [[[2], [3]]], [[4], [5]]]); // [0, 1, 2, 3, 4, 5]
console.log(resultIterative, "Iterative Result");
// Recursive Approach with Depth
const flattenRecursiveWithDepth = (arr, depth) => {
if (!Array.isArray(arr)) {
throw new TypeError("The first argument must be an array.");
if (depth === 0) return arr;
if (Array.isArray(ele) && depth > 0) {
result.push(...flattenRecursiveWithDepth(ele, depth - 1));
const result = flattenRecursiveWithDepth(
[[[[[0]]], [1]], [[[2], [3]]], [[4], [5]]], 1