javascript 通过递归来展平嵌套数组Ex:[1,2,3,[4,5,[7,8,[10,11,[12,13,[[[[[[14]]]]]]]]]] ]]

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 通过递归来展平嵌套数组Ex:[1,2,3,[4,5,[7,8,[10,11,[12,13,[[[[[[14]]]]]]]]]] ]]相关的知识,希望对你有一定的参考价值。

// Note: when we dont know how many time 
// we will have to pass trhou an array always use recursion

function flatten(nestedArray) {
    // we create the array where we will be adding 
    // the flatten elemnts from the array
    const newArray = []

    for(let i=0; i< nestedArray.length; i++){
        const thisItem = nestedArray[i]
        
        if(Array.isArray(thisItem)){
            console.log('Array item:',thisItem);
            // this loop would work only for [1,2,[3,4],5]
            // but no for [1,2,3,[4,5,[7,8,[10,11,[12,13]]]]]
            // for(let j=0; j < thisItem.length; j++){
            //     newArray.push(thisItem[j])
            // }

            //so in that case we can recursivly call flatten()
            // which will be taking the first nested array [4,5,[7,8,[10,11,[12,13]]]]
            // the next time will be sending [7,8,[10,11,[12,13]]]
            // adn so on
            
            const flatItem = flatten(thisItem)
            for(let j=0; j < flatItem.length; j++){
                newArray.push(flatItem[j])
            }

        }else{
            console.log('single item:', thisItem)
            newArray.push(thisItem)

        }

    }

    return newArray
}

console.log(flatten([1,2,3,[4,5,[7,8,[10,11,[12,13,[[[[[[14]]]]]]]]]]]))
//console.log(flatten([ 1, 2, 3, [4, 5], 6 ]))


// Time: O(n) => Each item is process once so is linear 
// Space: O(n) => Each item stored in the newArray is proportional to the amount of the input so is linear


以上是关于javascript 通过递归来展平嵌套数组Ex:[1,2,3,[4,5,[7,8,[10,11,[12,13,[[[[[[14]]]]]]]]]] ]]的主要内容,如果未能解决你的问题,请参考以下文章

如何在javascript中展平嵌套数组? [复制]

使用递归(并且不使用循环)展平嵌套数组

以递归方式展平包含未知级别的嵌套数组和映射的嵌套映射

Javascript递归数组展平

递归地展平数组(不循环)javascript

Javascript:使用递归将多维数组展平到位