SoFunction
Updated on 2025-03-01

Summary of the method of implementing array flattening by JS

Talk about it

I believe many friends have been asked about array flattening in some interviews. This is also a regular operation in our daily programming. It requires us to convert a multi-dimensional array into a one-dimensional array. Of course, I believe many friends can answer this question, but if the interviewer asks us to answer more, some friends may not be able to answer it. So, with this article, let’s summarize several ways to flatten arrays together today.

1. Ordinary recursive method

  • I believe that the first method of implementing array flattening solution that diggers can think of is to use recursive functions. This method checks whether it is still an array by iterating through each element in the array. If so, the subarray is flattened the same and the results are merged into the final one-dimensional array. For example:
let arr = [1,2,[3,4,[5,6]]]

function flattenArray(arr) {
  let result = []
  for (let i = 0; i < ; i++) {
    if ((arr[i])) {
      result = (flattenArray(arr[i]));
    } else {
      (arr[i])
    }
  }
  return result
}

(flattenArray(arr));  // [ 1, 2, 3, 4, 5, 6 ]

2. Reduce() method

  • use()The accumulator feature of the function, iterates through the array and merges the results of the subarray into the final one-dimensional array. In fact, it is also recursive, but it does not use the for loop like the above, which is not much different from the above code. Here we mainly use the reduce method, so the code is written more concise.
let arr = [1,2,[3,4,[5,6,[7,8]]]]

function flattenWithReduce(arr) {
  return ((acc, val) => 
    ((val) ? flattenWithReduce(val) : [val]),
    []
  );
}

(flattenWithReduce(arr)) // [1, 2, 3, 4, 5, 6, 7, 8]

advantage: Highly readable, clear logic, no need to create additional function closures.shortcoming: For very deep nested structures, the performance may not be as good as using the flat() method.

3. ()

  • ES6 has introducedflat()Method, you can directly flatten the array and specify the level depth of the flattening.
let arr = [1,2,[3,4,[5,6,[7,8,[9]]]]]

function flattenWithFlat(arr) {
  return (Infinity) // Infinity means completely flattening all levels}

(flattenWithFlat(arr)) // [1,2,3,4,5,6,7,8,9]

advantage: Simple and efficient, native support, suitable for modern browser environments.shortcoming: Older browsers do not support this method, polyfill or other compatibility solutions are required.

4. Extended operators and concat

  • Utilize extension operators (...) andconcat()Combined, gradually expand the nested array.
let arr = [1,2,[3,[4],[5,6,[7,8,[9]]]]]

function flattenWithSpread(arr) {
  while ((item => (item))) {
    arr = [].concat(...arr)
  }
  return arr
}

(flattenWithSpread(arr)); // [1,2,3,4,5,6,7,8,9]

advantage: The code is relatively concise and easy to understand.shortcoming: The number of loop executions depends on the depth of the array nesting and is relatively inefficient.

5. Breadth priority search and queue

  • This method uses breadth-first search, which is what we often call BFS strategy to flatten nested arrays. First create a queue and enqueue the original array as the initial node. Then enter the loop stage, as long as the queue is not empty, a layer of elements (i.e. all subarrays or values ​​of the current level) are taken from the head of the queue and check whether each element is an array. If it is an array, add its elements to the back of the queue one by one; if it is not an array, add the value directly to the result array. Loop until the queue is empty, and the result array contains all expanded one-dimensional elements.
let arr = [1,2,[3,[4],[5,6,[7,8,[9]]]]]

function flattenWithBFS(arr) {
  const queue = [arr] // Create a queue and initialize it into an array to be processed  const result = [] 

  while ( &gt; 0) { 
    const levelItems = () // Take out the element in the header of the queue    for (const item of levelItems) { // Iterate through each element of the current level      if ((item)) { 
        (item); 
      } else {
        (item) 
      }
    }
  }

  return result 
}

(flattenWithBFS(arr)) // [1,2,3,4,5,6,7,8,9]

advantage:

  • High space efficiency: By using the queue structure for hierarchical traversal, it is possible to ensure that any deep nested array is flattened within a limited number of loops.
  • No recursive call stack required: Compared with recursive methods, this method avoids stack overflow problems caused by deep nesting.

shortcoming:

  • Time complexity: Despite improvements over the method of extending operators combined with concat(), in extreme cases (e.g., very deep and wide tree structures), multiple iterations are required to completely flatten the array.
  • The code is relatively complex: Compared to the simple way of combining the extension operator with concat(), this method involves queue operations, which may take more time to understand.

6. Depth priority search and stack

  • This method uses the stack data structure for depth-first search, that is, DFS. First convert the original array to be processed into a stack and create an empty result array to store flattened one-dimensional elements. In a loop, as long as the stack is not empty, the current element is removed from the top of the stack. If the element is an array, all of its elements are pushed onto the stack; if it is not an array, it is added directly to the beginning of the result array. This process continues to go deeper into the bottom layer of the nested array, and then returns layer by layer until the stack is empty.
let arr = [1,2,[3,[4],[5,6,[7,8,[9]]]]]

function flattenWithDFS(arr) {
  const stack = [...arr] // Convert the original array to a stack  const result = [] 

  while ( &gt; 0) { // When there are elements pending in the stack    const current = () // Remove the element at the top of the stack
    if ((current)) { 
      (...current) // Push all its elements onto the stack    } else {
      (current) // Otherwise add non-array elements to the beginning of the result array    }
  }

  return result 
}

(flattenWithDFS(arr));  // [1,2,3,4,5,6,7,8,9]

advantage:

  • Recursive thought simplifies implementation: Depth-first search is naturally suitable for solving recursive problems. This method avoids explicit recursive calls, but still maintains the idea of ​​recursive processing.
  • No extra space complexity required: Compared with breadth-first search that requires the queue to save data at each level, depth-first search only requires one stack, which is more friendly to situations where memory resources are limited.

shortcoming:

  • Traversal order: Depth-first search may cause elements to be in different order in the flattened 1D array than in the original nested array.
  • Stack Overflow Risk: When facing extremely deep nested arrays, you may encounter stack overflow errors caused by JavaScript stack size limitations due to recursive simulation using the stack.

7. _.flattenDeep() of lodash library

  • The lodash library provides a ready-made method_.flattenDeep(), can handle nested arrays of any depth.
import _ from 'lodash'

let arr = [1,2,[3,[4],[5,6,[7,8,[9]]]]] 

const flattenedArr = _.flattenDeep(nestedArr)

(flattenedArr)

advantage: Third-party library packaging, powerful and optimized, suitable for various complex scenarios.shortcoming: Increase project dependence, not suitable for application scenarios that only require simple flatness and focus on performance and volume.

The above are seven common ways to flatten arrays. If you master these seven ways to flatten arrays, I believe you will be able to answer these questions easily. That’s all I’ll talk about today. As for the application scenarios of flattening arrays, this article does not introduce them. Of course, this is also a very important knowledge point. However, this article mainly summarizes some methods. Diggers who are interested in application scenarios can search for it themselves. If there are other methods of flattening arrays, please add them in the comment section.

This is the end of this article about the summary of JS method to implement array flattening. For more related JS array flattening content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!