SoFunction
Updated on 2025-03-01

Summary of six tips for implementing array flattening in javascript

Preface

This is how it is. I wrote an article a few months agoDaily front-end handwriting questions--day4, in which it discusses how to flatten an array in js. Then a big shot provided two clever solutions (see Method 5 and Method 6). I was shocked, so I sorted out the array flattening method I recommend for reference by all the big guys.

In daily use of JavaScript, handling multi-layer nested arrays is a common task. Read below to explore several ways to convert multidimensional arrays into one-dimensional arrays, each with its unique features.

Method 1: forEach and push

The fundamental idea of ​​array flattening is to expand multidimensional arrays into one-dimensional arrays. The first method adopts the classic recursion idea: iterate through each element in the array and determine whether it is an array. If it is not an array, push the element into the result array; if it is an array, the element of the array is recursively processed. The code example is as follows:

function _flat(targetArray, container = []) {
    if (!(targetArray)) return container;
    
    (item => {
        if (!(item)) {
            (item);
        } else {
            _flat(item, container);
        }
    });
    
    return container;
}

const rst = _flat([[[[[[1],2],3],4],5,6],7]);
('rst: ', rst);

Method 2:

In recent years, ES6 has been addedMethods, designed to simplify flattening operations. For this method, understanding its working principle is of great significance. It will only disassemble one layer of nested arrays by default. By looping to call until it cannot be expanded, we can get a completely flattened array.

function _flat2(targetArray) {
    if (!(targetArray)) return [];
    
    let _loop = targetArray;
    while (true) {
        const beforeFlat = _loop.length;
        const _Arr = _loop.flat();
        const afterFlat = _Arr.length;

        if (beforeFlat === afterFlat) return _Arr;
        _loop = _Arr;
    }
}

const rst2 = _flat2([[[[[[1],2],3],4],5,6],7]);
('rst2: ', rst2);

Method 3: findIndex and splice

The third method is usedas well as. First find the first array element in the array that has not yet been expanded, and then usespliceExpand it. This method changes the original array.

function _flat3(targetArray) {
    if (!(targetArray)) return [];
    
    while (true) {
        const arrItemIndex = (item => (item));
        if (arrItemIndex === -1) return targetArray;
        
        (arrItemIndex, 1, ...targetArray[arrItemIndex]);
    }
}

const rst3 = _flat3([[[[[[1],2],3],4],5,6],7]);
('rst3: ', rst3);

Method 4: stack

Using the data structure of the stack can be like traversal in the process. The specific operation is: put the source array into the stack as a whole, and then out the stack one by one to check whether it is an array. If it is an array, expand it and continue to put it into the stack; if it is not, put it into another stack to store the result. This approach is essentially the same as recursion, but using the stack can reduce operational complexity.

function _flat4(targetArray) {
    if (!(targetArray)) return [];
    
    const a = [...targetArray];
    const b = [];
    while () {
        const _tmp = ();
        if ((_tmp)) {
            (..._tmp);
        } else {
            (_tmp);
        }
    }
    
    return b;
}

const rst4 = _flat4([[[[[[1],2],3],4],5,6],7]);
('rst4: ', rst4);

Method 5: toString and split

This idea uses the arraytoStringmethod, which converts the array into a comma-separated string and then usessplitThe method gets the result array.

const arr = [1, [2, 3], 4, [[5]]];
const rst = ().split(',').map(item => +item);

toString()An interesting feature of the method is that it can convert multi-layer nested arrays into a flattened string separated by commas. In the form of a string, the nested structure information between each element in the array is lost, and only the element value is retained. For example, a like[1, [2, [3, [4]]]]array, bytoString()After the method is processed, it will become"1,2,3,4". This is exactly the one-dimensional form we expect, but it exists in the form of a string.

But this is not a complete solution. Although the string has been flattened, the array has not yet been formed. At this timesplit(',')The method comes in handy. It converts the string to an array again based on the comma separator, since the original nested structure has beentoString()Method erase, and the result array is a completely flat array. Finally, to ensure that the element type in the array is correct (becausesplit()Each element will be treated as a string), can be usedmap()Method converts each string element to its original type.

const arr = [1, [2, 3], 4, [[5]]];
const rst = ().split(',').map(item => +item);

In the above code,+itemis a quick trick to convert strings to numbers.

Method 6:

andis a powerful pair of methods that can be used to serialize and parse data. In JavaScript, these pairs are often used for deep copy operations, but they can also be used to flatten arrays.

The core idea is: first useConvert multidimensional arrays to string form while maintaining comma separation between array elements. At this time, the nested array is converted into a combination of brackets and commas. Next, through regular expressions.replace(/$|$/g, "")Remove all brackets in the string[], all that is left is commas and numbers. Finally, byReconstruct the processed string into a JavaScript array.

const arr = [1, [2, 3], 4, [[5]]];
const res = (arr).replace(/$|$/g, "");
const _a = ("[" + res + "]");

The beauty of this method is that it usesJSONThe serialization and parsing capabilities of objects simplify flattening operations. It should be noted that, sinceAll contents in the array (including numbers, strings, boolean values ​​andnull) is serialized into a string, so when using this method, you should ensure that the array does not contain elements other than the above types (such as functions or circular references), because these cannot be passedCorrect serialization.

After mastering these methods, you can choose the appropriate flattening method according to the specific situation. Each method has its applicable scenarios and performance considerations. By mastering these techniques, you can handle array flattening problems more freely in JavaScript.

This is the end of this article about the six tips for implementing array flattening by javascript. For more related content on javascript array flattening, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!