Skip to content

Instantly share code, notes, and snippets.

@sohailalam2
Created May 25, 2016 22:23
Show Gist options
  • Save sohailalam2/a1eb9f44f3ace560bafcd712416ffe29 to your computer and use it in GitHub Desktop.
Save sohailalam2/a1eb9f44f3ace560bafcd712416ffe29 to your computer and use it in GitHub Desktop.
// Using a wrapper function to prevent global namespace pollution
(function () {
var tempArray = [], // the final flattened array
idx = 0; // the position of elements in the flattent result array
/**
* A helper function to actually flatten the array
* @param array The given array as input
* @param inner A parameter to identify whether or not the function is recursively called
* @returns {*} Returns a flattened array
* @private
*/
function _flatten(array, inner) {
// if the input is not an array then it will return an empty array
if (!(array instanceof Array)) return [];
array.forEach(function (val, i) {
if (val instanceof Array)
tempArray.concat(_flatten(val, true));
else
tempArray[idx++] = val;
});
// create a deep copy of the flattened array
var result = tempArray.slice(0);
// if all elements were flattened, then clear the temporary array
if (!inner) {
tempArray = [];
idx = 0;
}
return result;
}
/**
* A prototype method on the Array object to flatten the given array.
* Usage:
* array.flatten()
*
* @returns {*} Returns a flattened array
*/
Array.prototype.flatten = function () {
return _flatten(this);
};
})();
// ------------------
// Usage and Examples:
// ------------------
console.log([].flatten());
console.log([[1, 2, [3]], 4].flatten());
console.log([[1], [2], [3, 4]].flatten());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment