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.
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;
}
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.