Created
June 18, 2017 10:11
-
-
Save jdittrich/5fc2a5037f267d14120547cadb23ff74 to your computer and use it in GitHub Desktop.
Create Tree, JS version
This file contains hidden or 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
//following adapted from https://stackoverflow.com/a/44185784/263398 | |
var data2 = [{ | |
name: "Children C1", | |
paths: [["A", "B", "C"],["A", "B"]] | |
}, { | |
name: "Children C2", | |
paths: [["A", "B", "C"]] | |
}, { | |
name: "Children C3", | |
paths: [["A", "B", "C"]] | |
}, { | |
name: "Children B1", | |
paths: [["A", "B"],["C"]] | |
}, { | |
name: "Children B2", | |
paths: [["A", "B"],["D", "E"],["X"]] | |
}, { | |
name: "Children A1", | |
paths: [["A"],["B"]] | |
}, { | |
name: "Children E1", | |
paths: [["D", "E"],["A", "B"]] | |
}]; | |
var tree2 = function(comments) { | |
var result = [], | |
initialValue = { | |
_: result | |
}; | |
comments.forEach(function(comment) { | |
//The accumulator = it is the accumulated value previously returned in the last invocation of the callback | |
comment.paths.forEach(function(path){ | |
console.log(path) | |
path.concat(comment.name).reduce(function(accumulator, pathpart, currentIndex, array) { | |
console.log("pathpart", pathpart) | |
if (!accumulator[pathpart]) { | |
console.log("IF!") | |
accumulator[pathpart] = { | |
_: [] | |
}; | |
accumulator._.push({ | |
name: pathpart, | |
children: accumulator[pathpart]._ | |
}); | |
} | |
//with every reduce step the nesting goas one level further down, since not the accumulator is returned, but its current next child object | |
console.log("accumulator") | |
return accumulator[pathpart]; | |
}, initialValue); | |
}); | |
}); | |
return result; | |
}(data2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment