Design & Download
Your JS Library
in Seconds!!!

Snippet: unnest() - Flatten Nested Structures

Written by Christopher West (cwest) on March 20, 2016.
Flatten a nested structure by representing the descendants in one array or object.
function unnest(arrOrObj, fn, opt_initial, opt_skipRecursives) {
  var initialIsArray = typeOf(opt_initial = opt_initial || (isArrayLike(arrOrObj) ? [] : {}), 'Array');
  function add(valueToAdd, opt_index) {
    if (opt_index == undefined && initialIsArray) {
      opt_initial.push(valueToAdd);
    }
    else {
      opt_initial[opt_index] = valueToAdd;
    }
  }
  function helper(parent, path, seen, seenCount) {
    var newPath;
    seen = [parent].concat(seen);
    seenCount++;
    function recurse(value) {
      for (var i = seenCount; i--;) {
        if (seen[i] === value) {
          if (opt_skipRecursives) {
            return;
          }
          throw new Error('Cannot unnest recursive, nested structures.');
        }
      }
      helper(value, newPath, seen, seenCount);
    }
    walk(parent, function(value, index) {
      fn(value, index, add, recurse, parent, newPath = path.concat([index]), arrOrObj);
    });
  }
  helper(arrOrObj, [], [], 0);
  return opt_initial;
}