Skip to content

Instantly share code, notes, and snippets.

@westc
Last active February 26, 2016 19:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save westc/0379e1b29a686d0e6710 to your computer and use it in GitHub Desktop.
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.
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