germancin
6/1/2018 - 5:42 AM

Flatten nested array by recursion Ex: [1,2,3,[4,5,[7,8,[10,11,[12,13,[[[[[[14]]]]]]]]]]]

Flatten nested array by recursion 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