Skip to content

Instantly share code, notes, and snippets.

@tomerweller
Last active February 17, 2017 06:00
Show Gist options
  • Save tomerweller/4382076afc9f7380b4c66a512a3726fa to your computer and use it in GitHub Desktop.
Save tomerweller/4382076afc9f7380b4c66a512a3726fa to your computer and use it in GitHub Desktop.
const inArr = [
{ order: 0.1, depth: 1 },
{ order: 0.2, depth: 1 },
{ order: 0.3, depth: 2 },
{ order: 0.4, depth: 2 },
{ order: 0.5, depth: 1 },
{ order: 0.6, depth: 2 },
{ order: 0.7, depth: 3 },
{ order: 0.8, depth: 1 },
];
const treeIt = (arr, rootDepth = 1) => {
return arr.reduceRight((acc, val) => {
if (val.depth === rootDepth) {
val.children = treeIt(acc.children, rootDepth + 1);
acc.result.unshift(val);
acc.children = [];
} else {
acc.children.unshift(val);
}
return acc;
}, {
result : [],
children: []
}).result;
};
console.log("result", treeIt(inArr));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment