christiannwamba
9/28/2016 - 9:09 PM

Flatten nested array with recurssion

Flatten nested array with recurssion

// Demo: http://jsbin.com/qaxurogowe/edit?html,js,console,output
// Recursive function
// which will continue to
// iterate through nested array until flattened
function flatten() {
    // A control variable
    // to hold flattened array
    var flat = [];
    // Begin a loop
    for (var i = 0; i < arguments.length; i++) {
        var el = arguments[i];
        if (el instanceof Array) {
            // If the element is of type Array
            // flatten and push to flat
            flat.push.apply(flat, flatten.apply(this, el));
        } else {
            // if not of type Array
            // just push the item
            flat.push(arguments[i]);
        }
    }
    // Returned flattened array
    return flat;
}