Skip to content

Instantly share code, notes, and snippets.

@rrmhearts
Last active July 20, 2020 15:29
Show Gist options
  • Save rrmhearts/d7dcd861db51551704f16282014e8d4b to your computer and use it in GitHub Desktop.
Save rrmhearts/d7dcd861db51551704f16282014e8d4b to your computer and use it in GitHub Desktop.
Create a flat list of nodes from a nested tree structure.
// nestedTree is a tree structure containing subtrees under "nodes" property. d=1 is the default "depth of the tree"
function flatDeep(arr, d = 1) {
return d > 0 ? arr.reduce((acc, val) => acc.concat(Array.isArray(val.nodes) ? flatDeep(val.nodes, d - 1) : val), [])
: arr.slice();
};
let flat = flatDeep(nestedTree, Infinity);
// Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment