Last active
February 17, 2017 06:00
-
-
Save tomerweller/4382076afc9f7380b4c66a512a3726fa to your computer and use it in GitHub Desktop.
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
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