Recursively Flatten JavaScript Array

I have started a series on the recursive problem with visualisation so that It’s easy to understand. In this problem, I will show you how to flat nested array objects using javaScript with visualisation.

Let’s suppose you have the following function(fn), which accepts a nested array as arguments, and then it flats the array into a single array.

Input

fn([1,[2,[3],4]])

Output
1,2,3,4

The above example is perfect for recursion.

function flatten(ary) {
  var ret = [];
    for(var i = 0; i < ary.length; i++) {
        if(Array.isArray(ary[i])) {
            ret = ret.concat(flatten(ary[i]));
        } else {
            ret.push(ary[i]);
        }
    }
    return ret;
} 
$ads={1}

Let’s understand the code line by line.

  • A first-time function call is flatten([2,[3],4]
  • Then it calls flatten([3] because three is the array
  • In the final call, the last function returns three and append to the result

See the visualisation to understand how to recursive function tree is generated.

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post