Flatten with concat.apply
Write a JavaScript function that flattens a nested array one level deep using Array.prototype.concat.apply(). The function takes an array of arrays and returns a new array containing all elements from the sub-arrays concatenated together.
The concat.apply pattern is a classic JavaScript technique: [].concat.apply([], nestedArray) works because concat accepts multiple arguments, and apply spreads the sub-arrays as individual arguments. Each sub-array becomes a separate argument to concat, which merges them into a single flat array. This is the most concise pre-ES6 way to flatten one level.
In ES6+, the spread operator provides a more readable alternative: [].concat(...nestedArray). Both approaches leverage JavaScript's ability to pass arrays as individual arguments to functions. Understanding this pattern is essential for working with nested data structures in real-world JavaScript applications.
Time complexity is O(n) where n is the total number of elements across all sub-arrays. Space complexity is O(n) for the result array. The concat method creates a new array without modifying the original nested structure.
Edge cases include an empty outer array (return empty array), empty sub-arrays (their elements are not added), and ensuring the flattening only goes one level deep (not recursive flattening).
Example Input & Output
Single nested array
Each sub-array has one element
Empty array
Some sub-arrays empty
Flatten one level
Algorithm Flow

Solution Approach
Recursively flatten a nested array into a single-level array. Use recursion: iterate through each element; if the element is an array, recursively flatten it and concatenate to the result; otherwise, add it directly.
This recursive approach handles nested arrays of arbitrary depth. The base case is a non-array element which is pushed directly.
Time O(n), Space O(n).
Best Answers
function solution(nested) {
return [].concat.apply([], nested);
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
