tvvignesh
10/15/2016 - 4:47 PM

Flatten an array of nested arrays of integers

Flatten an array of nested arrays of integers

/**
 * Flatten an Array of Arbitrarily nested Arrays of Integers
 * into a Flat Array of Integers.
 * @param  {Array} intArray - Array of Numbers
 * @param  {Array} flatArray  - Flatten array (recursive)
 * @return {Array}                - Array of Numbers
 * 
 * Link to JSBin - http://jsbin.com/dofuneb/edit?js,output
 */
var flatten = function(intArray, flatArray) {
    // Keep previous results if recursive
    var results = flatArray || [];

    if (intArray && intArray.length > 0) {
        intArray.forEach(function(value) {
            if (typeof value === 'number') {
                results.push(value);
            } else if (value instanceof Array) {
                flatten(value, results);
            }
        });
    }

    // Flat array of numbers after evaluation
    return results;
};