Skip to content

Instantly share code, notes, and snippets.

@specificityy
Last active September 4, 2015 23:46
Show Gist options
  • Save specificityy/6918111efafdc9c207ad to your computer and use it in GitHub Desktop.
Save specificityy/6918111efafdc9c207ad to your computer and use it in GitHub Desktop.
Function that flattens an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4].
/**
* Flattens the passed in array.
*
* @param {Array} array The array to flatten.
* @param {boolean} isDeep Specify a deep flatten.
* @returns {Array} Returns the new flattened array.
*/
function flatten(array, isDeep) {
var index = -1,
length = array.length,
result = [];
while (++index < length) {
var value = array[index];
if (Array.isArray(value)) {
// Recursively flatten arrays (susceptible to call stack limits)
result = result.concat(isDeep ? flatten(value, isDeep) : value);
} else {
result.push(value);
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment