
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].
- The array contains elements: 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].
- The array contains elements: 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
Editorial
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. |
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