DEV Community

Cover image for Flatten Deeply Nested Array
Kush Bhandari
Kush Bhandari

Posted on

Flatten Deeply Nested Array

let arrItem=[1,[2,3,[4,5],[5,[3,[29]]]]];

I was asked in the interview to flatten this array meaning convert this array into something like this [1,2,3,4,5,5,3,29];

So, my first approach was to use a inbuild flat method of array.

arrItem.flat()

Now, the problem with this is it doen't flat deeply nested array. So you have to provide the depth. Here we can provide depth as infinity. So the answer would be.

arrItem.flat(Infinity)

Now, the interviewer will ask for a custom implementation of flat method.

There are two approach to do so.
1) Recursive Approach

Array.prototype.flattenArray=function(){
    // This is recursion Approach
    let array=this;
    let output=[];
    function flatArray(array){
        for(let item of array){
            if(Array.isArray(item)){
                flatArray(item)
            }
            else {
                output.push(item)
            }
        }
    }
    flatArray(array)
    return output;
}
Enter fullscreen mode Exit fullscreen mode

2) Using Stack

let arrItem=[1,[2,3,[4,5],[5,[3,[29]]]]];

Array.prototype.flattenArray = function(depth=1){
    let stack=[];
    let output=[];
    for(let i=this.length-1;i>=0;i--){
        stack.push([this[i],depth])
    }    

    while(stack.length){
        let [item,depth]=stack.pop();
        if(Array.isArray(item) && depth>0){
            for(let i=item.length-1;i>=0;i--){
              stack.push([item[i],depth-1]);
            }
        }
        else {
            output.push(item);
        }
    }
    return output

}

console.log(arrItem.flattenArray(2)); // Provide any depth here for nesting. Infinity,for deeply nested.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)