Skip to content

Instantly share code, notes, and snippets.

@matthewp
Last active December 17, 2015 12:29
Show Gist options
  • Save matthewp/5609985 to your computer and use it in GitHub Desktop.
Save matthewp/5609985 to your computer and use it in GitHub Desktop.
Array flatten
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