Last active
July 20, 2020 15:29
-
-
Save rrmhearts/d7dcd861db51551704f16282014e8d4b to your computer and use it in GitHub Desktop.
Create a flat list of nodes from a nested tree structure.
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
// 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