SoFunction
Updated on 2025-04-12

Collection of methods for flattening JS arrays (recursive, while loop, flat)

Preface

Array flattening is also one of the common interview questions. Today I will briefly share with you the common array flattening methods. This question actually mainly examines the idea of ​​recursion, because when an array is nested with a very multi-layer array, it can only be flattened through loop recursion. This sharing is mainly about sharing the recursive thoughts of this question. Without further ado, start sharing!

flat() method

The first method must be a method that comes with js.flatIt is a method of the Array object in JavaScript. It is used to flatten multi-dimensional arrays, that is, convert a nested multi-layer array into an array with only one layer. This method was introduced in ECMAScript 2019 (ES10).
flatThe method can accept an optional parameterdepth, used to specify the depth of flattening.

  • No parameters or transmission1When  , the first layer nested array is flattened by default.
  • Incoming numbersnIndicates flattening the array to the firstnLayer depth.
  • If passed inInfinityAs a parameter, no matter how deep the nest is, it will be flattened into a one-dimensional array.

Here are some examples

let arr = [1,[2,[3,[4,5]]]];
// It will only flatten one layer((1));//[1,2,[3,[4,5]]]
// Two flat layers((2));//[1,2,3,[4,5]]
// All flat((Infinity));//[1,2,3,4,5]

toString() method

A cold knowledge, array oftoStringMethods separate elements with commas, meaning no matter how many layers you nest,toStringAll methods can be used to separate you into commas, which just meets our requirements.

let arr = [1,[2,[3,[4,5]]]];
//The toString method becomes a string(());//'1,2,3,4,5'
arr = ().split(",").map(function (item){
    return +item;
})

recursion

Here is a brief introduction to the idea when you encounter aUnknown range of data(I don't know how many layers of arrays are nested), only useLoop or recurse to perform all ranges traversals, although the recursion is relatively poor in performance because it needs to be continuouslyCreate a context into the execution stack. But I have to say that recursion is really cool!

Pure handwriting recursion

let arr = [1,[2,[3,[4,5]]]];
function flatten(arr) {
    //Create an array and accept flattened array    let result = [];
    for(let i=0,len=;i<len;i++){
    // If the child element is an array        if((arr[i])){
        // Flatten the child elements and add them to the result array            result = (flatten(arr[i]));
        }else{
        // Add child elements directly if they are not arrays            (arr[i]);
        }
    }
    return result;
}
(flatten(arr));//[1,2,3,4,5]

Recursive method (less code)

I'm afraid some friends don't know about itreduceHere is a brief introduction to the usage.reduceThe function will traverse each element, and each time iterates, a callback function will be executed. The function has two parameters, one is the value returned by the last callback function, and the other is the value of the current element. You can give the initial value. If you don't give it, the default initial value is the first element, and then iterate from the second element. Finally, return the value returned by the last callback function. Here is a simple case of reduce

let arr = [1,2];
(((sum,nowVal)=>sum+nowVal))//    3
(((sum,nowVal)=>sum+nowVal,4))//  4

After a brief understanding of reduce, we will start recursive flat arrays

let arr = [1,[2,[3,[4,5]]]];
function flatten(arr){
    // Same as ordinary recursion, here is just a reduction in the code and the idea is consistent    return ((result,nowValue)=>
    (nowValue)?(flatten(nowValue)):(nowValue),[]);
}
(flatten(arr));// [1,2,3,4,5]

While loop

Although recursion is really good, I still need to introduce loops. This article uses the structural method of arrays. Destruction in JavaScript is an expression that allows you to extract data from an array or object and assign it to a variable. This feature was introduced by ES6 (ECMAScript 2015), greatly improving the simplicity and readability of the code. Here is a simple example:

let arr = [1,2,3,[4,5]];
let [first,...rest]=arr;//first is 1, the rest here will store the remaining elements [2,3,[4,5]]

Then the next step is the array flat!

let arr = [1,[2,[3,[4,5]]]];
function flatten(arr){
    let result = [];
    while(!=0){
        // Take out the first element of arr and save the rest into the rest array        let [first,...rest] = arr;
        if((first)){
        //If it is an array, then deconstruct the first and add the elements inside to the arr one by one.        //It is equivalent to lowering the elements in first by one level, rest must be deconstructed and added        // Otherwise, the element level in rest will be upgraded        arr = [...first,...rest];
        }else{
        //If the first element is not an array, add it to the result array        (first);
        //This is equivalent to removing the first element and taking the first element of the rest array next time you traverse iterate.        arr =[...rest];
        }
    }
    return result;
}
(flatten(arr));// [1,2,3,4,5]

Conclusion

This is the article about JS array flattening methods (recursion, while loop, flat) that introduces this. 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!