Javascript Flatten an n-dimension array iteratively and recursivley

Javascript Flatten an n-dimension array iteratively and recursivley

Just in case you need to know

Recursively, although a tad more elegant this will blow your stack up until ES6

var data = [ 1, [ 2, 3 ], [4, [ 5, [ 6, 7 ], 8 ], 9] ];
 
function flatten( flattenMe ) {    
    var answer = [];
    function doWork( flattenMe ) {
        for( var i =0, l = flattenMe.length; i<l; i++ ) {
            var element = flattenMe[ i ]; 
            if( typeof element  === "object" && element instanceof Array ) {
               doWork( element );
            }
            else {
                answer.push( element );
            }
        }
    }
    doWork( flattenMe );
    return answer;
}
 
//iterative solution, needs a bit of optimization
function iterativeFlatten( flattenMe ) {
 
   var flattened = [],
       que = [],
       element = "";
 
   que = flattenMe;
   while( que.length ) {
       //get the next element off the que
       element = que.shift();
       //check its type if its another array push its elements on the que
       if( element.constructor == Array){
           var temp = que;
           que = []
           for( var i = 0, l = element.length; i<l; i++ ){
               que.push( element[i] );
           }
           que =  que.concat(temp);
       }
       //else its a primitive push it on the flattened array
       else {
           flattened.push(element)
       }
 
   }
 
   return flattened
 
}
This entry was posted in Uncategorized. Bookmark the permalink.