Last active
September 4, 2015 23:46
-
-
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].
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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