Recursively Flatten JavaScript Array

I have started a series of recursive problems. I will show you how to flatten the javascript array in this problem. This example is for nested array objects. I have added the visualization, which will help understand the recursive part.

Let’s suppose you have the following function. fn Which accepts a nested array as arguments and then flat the array into a single array.




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 {
    return ret;

Let's understand the code line by line

  • The 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 3 and appends to the result.

Next Post Previous Post
No Comment
Add Comment
comment url