Tutorialspoint
Problem
Solution
Submissions

Array Flattening

Certification: Basic Level Accuracy: 25% Submissions: 4 Points: 5

Write a JavaScript program to flatten a single-level nested array. Given an array that contains other arrays as elements, convert it into a single flat array containing all the individual elements. For example, [1, [2, 3], 4, [5, 6]] should become [1, 2, 3, 4, 5, 6].

Example 1
  • Input: arr = [1, [2, 3], 4, [5, 6]]
  • Output: [1, 2, 3, 4, 5, 6]
  • Explanation:
    • The array contains elements: 1, [2, 3], 4, [5, 6].
    • Element 1 is a number, keep it as is.
    • Element [2, 3] is an array, extract 2 and 3.
    • Element 4 is a number, keep it as is.
    • Element [5, 6] is an array, extract 5 and 6.
    • Final flattened array: [1, 2, 3, 4, 5, 6].
Example 2
  • Input: arr = [10, [20], [30, 40], 50]
  • Output: [10, 20, 30, 40, 50]
  • Explanation:
    • The array contains elements: 10, [20], [30, 40], 50.
    • Element 10 is a number, keep it as is.
    • Element [20] is an array with one element, extract 20.
    • Element [30, 40] is an array, extract 30 and 40.
    • Element 50 is a number, keep it as is.
    • Final flattened array: [10, 20, 30, 40, 50].
Constraints
  • 1 ≤ arr.length ≤ 1000
  • Array elements can be numbers or single-level nested arrays
  • No deep nesting (only one level of nesting allowed)
  • Time Complexity: O(n) where n is total number of elements
  • Space Complexity: O(n) for the result array
ArraysShopifySamsung
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

  • Create an empty result array to store flattened elements
  • Iterate through each element of the input array
  • Check if the current element is an array using Array.isArray()
  • If it's an array, iterate through its elements and add them to result
  • If it's not an array, directly add the element to result
  • Return the flattened result array

Steps to solve by this approach:

 Step 1: Initialize an empty result array to store the flattened elements.
 Step 2: Start iterating through each element of the input array.
 Step 3: For each element, check if it is an array using Array.isArray() method.
 Step 4: If the element is an array, iterate through all its sub-elements.
 Step 5: Add each sub-element to the result array using push() method.
 Step 6: If the element is not an array, directly add it to the result array.
 Step 7: Continue this process for all elements and return the final flattened array.

Submitted Code :