Code Logo

Flatten with concat.apply

Published at25 Jul 2026
JavaScript Data Structures Medium 0 views
Like0

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

Example 1
Input
[[1,2,3]]
Output
[1,2,3]
Explanation

Single nested array

Example 2
Input
[[1],[2],[3]]
Output
[1,2,3]
Explanation

Each sub-array has one element

Example 3
Input
[]
Output
[]
Explanation

Empty array

Example 4
Input
[[], [1], []]
Output
[1]
Explanation

Some sub-arrays empty

Example 5
Input
[[1,2],[3,4],[5]]
Output
[1,2,3,4,5]
Explanation

Flatten one level

Algorithm Flow

Recommendation Algorithm Flow for Flatten with concat.apply
Recommendation Algorithm Flow for Flatten with concat.apply

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.

function flatten(arr) {
  var result = [];
  for (var i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) result = result.concat(flatten(arr[i]));
    else result.push(arr[i]);
  }
  return result;
}

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

javascript - Approach 1
function solution(nested) {
  return [].concat.apply([], nested);
}