Last active
December 17, 2015 12:29
-
-
Save matthewp/5609985 to your computer and use it in GitHub Desktop.
Array flatten
This file contains hidden or 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
function flatten(array, isShallow, callback, thisArg) { | |
var index = -1, | |
length = array ? array.length : 0, | |
result = []; | |
// juggle arguments | |
if (typeof isShallow != 'boolean' && isShallow != null) { | |
thisArg = callback; | |
callback = !(thisArg && thisArg[isShallow] === array) ? isShallow : undefined; | |
isShallow = false; | |
} | |
if (callback != null) { | |
callback = lodash.createCallback(callback, thisArg); | |
} | |
while (++index < length) { | |
var value = array[index]; | |
if (callback) { | |
value = callback(value, index, array); | |
} | |
// recursively flatten arrays (susceptible to call stack limits) | |
if (isArray(value)) { | |
push.apply(result, isShallow ? value : flatten(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