Last active
February 26, 2016 19:53
-
-
Save westc/0379e1b29a686d0e6710 to your computer and use it in GitHub Desktop.
Convert a tree-like array into a flat array where the nested values are all part of the top-most array.
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
function unnestArray(arr, callback) { | |
function recurse(arr, path) { | |
function f(arr, opt_insertBefore) { | |
dontAddRet = dontAddRet || !arguments.length; | |
if (arr) { | |
results.push.apply(opt_insertBefore ? results : after, recurse(arr, curPath)); | |
} | |
} | |
for (var ret, dontAddRet, curPath, results = [], after = [], i = 0, l = arr.length; i < l; i++) { | |
dontAddRet = 0; | |
ret = callback(arr[i], f, curPath = path.concat([i]), arr); | |
results = results.concat(dontAddRet ? [] : [ret], after.splice(0)); | |
} | |
return results; | |
} | |
return recurse(arr, []); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment