Tutorialspoint
Problem
Solution
Submissions

Flatten Deeply Nested Array

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a JavaScript function to flatten a deeply nested array without using any built-in methods like Array.flat() or Array.concat(). The function should take a nested array of any depth and return a single-dimensional array containing all elements in their original order.

Example 1
  • Input: arr = [1, [2, 3], [4, [5, 6]], 7]
  • Output: [1, 2, 3, 4, 5, 6, 7]
  • Explanation:
    • The input array contains nested arrays at different levels.
    • We traverse through each element and check if it's an array.
    • If an element is an array, we recursively flatten it.
    • All elements are collected in a single flat array.
    • The result maintains the original order of elements.
Example 2
  • Input: arr = [[[1, 2]], [3, [4, [5]]]]
  • Output: [1, 2, 3, 4, 5]
  • Explanation:
    • The input has multiple levels of nesting.
    • We recursively process each nested array.
    • Elements 1 and 2 are extracted from the triple-nested array.
    • Elements 3, 4, and 5 are extracted from their respective nested positions.
    • All elements are combined into a single flat array.
Constraints
  • The array can contain any type of elements (numbers, strings, objects, etc.)
  • The nesting depth can be arbitrary
  • You cannot use built-in flattening methods like Array.flat(), Array.concat()
  • Time Complexity: O(n) where n is the total number of elements
  • Space Complexity: O(d) where d is the maximum depth of nesting
ArraysRecursionIBMHCL Technologies
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use recursion to handle nested arrays at any depth
  • Check if each element is an array using Array.isArray()
  • If the element is an array, recursively call the flatten function
  • If the element is not an array, add it directly to the result
  • Use the spread operator or push method to combine results

Steps to solve by this approach:

 Step 1: Initialize an empty result array to store flattened elements.
 Step 2: Iterate through each element in the input array.
 Step 3: Check if the current element is an array using Array.isArray().
 Step 4: If it's an array, recursively call the flatten function and concatenate results.
 Step 5: If it's not an array, push the element directly to the result array.
 Step 6: Continue until all elements are processed.
 Step 7: Return the flattened result array.

Submitted Code :