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 how to flatten a multi dimensional array.

Recursively, although a tad more elegant this could blow your stack up if data.length === huge.  ES6 fixes the recursion problem.

var data = [ 1, [ 2, 3 ], [4, [ 5, [ 6, 7 ], 8 ], 9] ];
//recursive
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;
}
//Iterativley do the same thing
function flati( data ){
    var flat = [];
    while( data.length ) {
 
        var currentEl = data.shift();
        if( Array.isArray( currentEl ) ){
            data = currentEl.concat(data)
        }
        else{
            flat.push( currentEl )
        }
    } 
    return flat;
}
This entry was posted in Uncategorized. Bookmark the permalink.